C# 从 linq 查询填充数据表
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 
原文地址: http://stackoverflow.com/questions/17088779/
Warning: these are provided under cc-by-sa 4.0 license.  You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Fill Datatable from linq query
提问by Shantanu Sen
i am using the below code
我正在使用下面的代码
IEnumerable<DataRow> query = from c in at.appointmentcalendars.AsEnumerable() 
                             select c;
DataTable dt = query.CopyToDataTable();
But i am getting the below error
但我收到以下错误
Cannot implicitly convert type
'System.Collections.Generic.IEnumerable<appointmentcalendar>'to'System.Collections.Generic.IEnumerable<System.Data.DataRow>'. An explicit conversion exists (are you missing a cast?)
无法将类型隐式转换
'System.Collections.Generic.IEnumerable<appointmentcalendar>'为'System.Collections.Generic.IEnumerable<System.Data.DataRow>'. 存在显式转换(您是否缺少演员表?)
采纳答案by terrybozzio
Since the query returns an IEnumerable of Type DataRow, you have to specify what to insert into the datatable, in this case DataRow.
由于查询返回类型为 DataRow 的 IEnumerable,您必须指定要插入到数据表中的内容,在本例中为 DataRow。
DataTable dt = query.CopyToDataTable<DataRow>();
If you used
如果你使用
var query = //linq query of what you need for new datatable....
DataTable dt = query.CopyToDataTable();
Your table name is dt so select what you need from the original dt
你的表名是 dt 所以从原来的 dt 中选择你需要的
var query = from c in db.something
            where c.othersomething == "onlyyouknow"
            orderby c.othersomething
            select new { NewObject = c.othersomething };
DataTable MyDataTable = new DataTable();
myDataTable.Columns.Add(
    new DataColumn()
    {
        DataType = System.Type.GetType("System.String"),//or other type
        ColumnName = "Name"      //or other column name
    }
);
foreach (var element in query)
{
    var row = MyDataTable.NewRow();
    row["Name"] = element.NewObject;
    myDataTable.Rows.Add(row);
}
回答by Sergey Berezovskiy
at.appointmentcalendarsis not a DataTable. Thus your query returns collection of appointmentcalendarobjects, which cannot be cast to a collection of DataRow. 
at.appointmentcalendars不是DataTable. 因此,您的查询返回appointmentcalendar对象的集合,这些对象不能转换为DataRow.
You need to use CopyToDataTablemethod from MSDN article How to: Implement CopyToDataTable Where the Generic Type T Is Not a DataRow:
您需要使用CopyToDataTableMSDN 文章How to: Implement CopyToDataTable Where The Generic Type T Is Not a DataRow 中的方法:
IEnumerable<appointmentcalendar> query = at.appointmentcalendars.AsEnumerable();
DataTable dt = query.CopyToDataTable();
Default CopyToDataTable()method works only with collection of DataRowobjects, so you can't use it here.
默认CopyToDataTable()方法仅适用于DataRow对象集合,因此您不能在此处使用它。
回答by Suman Guha
If some one need the solution in VB.net and with Aggregate Functions:
如果有人需要 VB.net 和聚合函数中的解决方案:
    Dim MyDataTable As DataTable = New DataTable
    MyDataTable.Columns.Add("ProviderName", GetType(String))
    MyDataTable.Columns.Add("TotalNumSale", GetType(Integer))
    MyDataTable.Columns.Add("TotalValSale", GetType(Double))
    Dim testquery = (From p In adviceProductData _
                                         Where p.IsOffPanel = False _
                                   Group By p.ProviderName _
                                   Into _
                                   totalNoOfSale = Sum(p.NoOfSales), _
                                   totalValueOfSale = Sum(p.ValueOfSales)
                                   Select New With {
                                       .ProvName = ProviderName,
                                        .TotSale = totalNoOfSale,
                                       .TotVal = totalValueOfSale
                                       }).ToList()
    Dim item
    For Each item In testquery
        Dim row = MyDataTable.NewRow()
        row("ProviderName") = item.ProvName
        row("TotalNumSale") = item.TotSale
        row("TotalValSale") = item.TotVal
        MyDataTable.Rows.Add(row)
    Next
回答by Ata Hoseini
DataTable getListRow(DataTable dt, int intSndBCode, int intPostManSCode)
    {
        IEnumerable<DataRow> results = (from MyRows in dt.AsEnumerable()
                       where
                       MyRows.Field<int>("m_sndBCode") == intSndBCode
                       &&
                       MyRows.Field<int>("m_postManSCode") == intPostManSCode
                       select MyRows);
        DataTable dtNew = results.CopyToDataTable();
        return dtNew;
    }

