Fastest way to fill DataTable from LINQ query using DataContext

后端 未结 1 1098
旧时难觅i
旧时难觅i 2021-01-02 13:25

I am trying to run a linq query but I need the result as a datatable as I am using that to store records from different queries in the same viewstate object.

The 2 v

1条回答
  •  陌清茗
    陌清茗 (楼主)
    2021-01-02 14:06

    Your problem is this:

    as IEnumerable
    

    The as keyword performs a safe cast, not a conversion, which it seems like you might think that it's doing. The as keyword is semantically the same as doing this:

    IEnumerable queryProjects = 
        (IEnumerable)(from DataRow p in db.STREAM_PROJECTs.AsEnumerable()
        where p.Field("STREAM_ID") == StreamID
        select new
        {
            PROJECT_ID = p.Field("PROJECT_ID"),
            PROJECT_NAME = p.Field("PROJECT_NAME")
        });
    

    Except the version with as won't throw an exception when it fails to cast your query object (which is an IQueryable, where T is an anonymous type) to an IEnumerable (which it isn't).

    Unfortunately, there is no built-in method that I'm aware of that will take an enumerable of a concrete type (like your anonymous type in this example) and turn it into a DataTable. Writing one wouldn't be too complicated, as you'd essentially need to get the properties reflectively then iterate over the collection and use those properties to create columns in a DataTable. I'll post an example in a few.

    Something like this, placed in a static class within a namespace that you're using, should provide an extension method that will do what you want:

    public static DataTable ToDataTable(this IEnumerable source)
    {
        PropertyInfo[] properties = typeof(T).GetProperties();
    
        DataTable output = new DataTable();
    
        foreach(var prop in properties)
        {
            output.Columns.Add(prop.Name, prop.PropertyType);
        }
    
        foreach(var item in source)
        {
            DataRow row = output.NewRow();
    
            foreach(var prop in properties)
            {
                row[prop.Name] = prop.GetValue(item, null);
            }
    
            output.Rows.Add(row);
        }
    
        return output;
    }
    

    0 讨论(0)
提交回复
热议问题