How to populate DataTable with anonymous LINQ result

前端 未结 3 386
误落风尘
误落风尘 2020-12-21 00:49

I have the following LINQ query:

var timesheets = from timesheet in entities.Timesheets
    join timesheetTask in entities.Timesheet_Task on timesheet.Id e         


        
相关标签:
3条回答
  • 2020-12-21 01:27

    I'm using FastMember for this purpose. It uses IL instead of reflection (much faster) to iterate over all of the property and field values automatically. Code sample from the site:

    IEnumerable<SomeType> data = ...
    var table = new DataTable();
    using(var reader = ObjectReader.Create(data))
    {
        table.Load(reader);
    }
    
    0 讨论(0)
  • 2020-12-21 01:44

    If you really want to populate DataTable:

    // your query
    var timesheets = ...
    
    // design table first
    DataTable table = new DataTable();
    table.Columns.Add(new DataColumn
        {
            ColumnName = "TaskName",
            DataType = typeof(String);
        });
    ...
    
    List<DataRow> list = new List<DataRow>();
    foreach (var t in timesheets)
    {
        var row = table.NewRow();
        row.SetField<string>("TaskName", t.taskName); // extension method from System.Data.DataSetExtensions.dll
        ...
    
        list.Add(row);
    }
    
    DataTable table = list.CopyToDataTable(); // extension method too
    

    Or more LINQ way:

    timesheets
        .Select(t =>
            {
                var row = table.NewRow();
                ...
                return row;
            })
        .CopyToDataTable();
    

    Or in same query syntax. Implement a method:

    static DataRow NewRow(DataRow row, string taskName, ....)
    {
        ...
    }
    

    Then query itself:

    (from ...
     where ...
     select NewRow(table.NewRow(), task.Name, ...)
    ).CopyToDataTable();
    
    0 讨论(0)
  • 2020-12-21 01:48

    Call .ToList().
    The resulting List<T> can also be bound to a DataGridView, and is easier to work with than a DataTable.

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