Tuesday, July 22, 2014

Convert Linq2SQL Result To DataTable

I met a situation I need to convert Linq2SQL result to DataTable so I can take advantage of the GridView sorting ( binding to datatable instead of binding to list )etc.


Here is the sample code to do it with Reflection:



            DataTable dataTable = new DataTable();

            foreach (var prop in typeof(xxx_get_xxxxboardResult).GetProperties())
            {
                Type type = prop.PropertyType;
             
                 ////////////////////////////////////////////////////////////////////////////////
                //Nullable Type would throw error if without this below
                if (type.IsGenericType && type.GetGenericTypeDefinition() == typeof(Nullable<>))
                    type = Nullable.GetUnderlyingType(prop.PropertyType);


                dataTable.Columns.Add(prop.Name, type);
            }
         
            ISingleResult<xxx_get_xxxxResult> linq2SQLResult = null;
            using (System.Data.Linq.DataContext context = new System.Data.Linq.DataContext())
            {
                linq2SQLResult = context.xxx_get_xxxxboard(city);

                foreach (var advisor in linq2SQLResult.ToList())
                {
                    DataRow dataraw = dataTable.NewRow();

                    foreach (var prop in typeof(xxx_get_xxxxboardResult).GetProperties())
                    {
                        dataraw[prop.Name] = typeof(xxx_get_xxxxboardResult).GetProperty(prop.Name).GetValue(advisor,null);
                    }
                 
                    dataTable.Rows.Add(dataraw);
                }

            }

No comments:

Post a Comment