convert linq query results to datatable C#

前端 未结 3 394
无人及你
无人及你 2020-12-21 05:06

I want to convert the linq query results to datatable so that I can assign datatable to GridView to show it on asp page.

However I am not able to convert the results

3条回答
  •  清歌不尽
    2020-12-21 05:27

    If you want to have you own extension method then you could always do something like this:

        public static DataTable ToDataTable(this IQueryable items)
        {
            Type type = typeof(T);
    
            var props = TypeDescriptor.GetProperties(type)
                                      .Cast()
                                      .Where(propertyInfo => propertyInfo.PropertyType.Namespace.Equals("System"))
                                      .Where(propertyInfo => propertyInfo.IsReadOnly == false)
                                      .ToArray();
    
            var table = new DataTable();
    
            foreach (var propertyInfo in props)
            {
                table.Columns.Add(propertyInfo.Name, Nullable.GetUnderlyingType(propertyInfo.PropertyType) ?? propertyInfo.PropertyType);
            }
    
            foreach (var item in items)
            {
                table.Rows.Add(props.Select(property => property.GetValue(item)).ToArray());
            }
    
            return table;
        }
    

    You will need to reference both of these

    using System.ComponentModel;
    using System.Data;
    

提交回复
热议问题