填补LINQ查询的数据表 [英] Fill Datatable from linq query

查看:162
本文介绍了填补LINQ查询的数据表的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我用下面的代码



 的IEnumerable<&的DataRow GT;查询=从C在at.appointmentcalendars.AsEnumerable()
选择C;

DataTable的DT = query.CopyToDataTable();



但我提示以下错误:



<块引用>

无法隐式转换
'System.Collections.Generic.IEnumerable< appointmentcalendar>
System.Collections.Generic.IEnumerable<&的System.Data.DataRow GT; 。一个
显式转换存在(是否缺少强制转换?)



解决方案

由于该查询返回类型的DataRow的IEnumerable,你必须指定什么插入到数据表,在这种情况下的DataRow。

 数据表DT = query.CopyToDataTable<&的DataRow GT;(); 

如果您使用



你需要什么新的DataTable .... 
DataTable的DT = query.CopyToDataTable VAR的查询= // LINQ查询();

您表的名称是DT所以选择从原来的DT

$ B $需要什么b

  VAR的查询=从C在db.something 
其中c.othersomething ==onlyyouknow
排序依据c.othersomething
。选择所需的新{NewObject的= c.othersomething};

的DataTable MyDataTable =新的DataTable();
myDataTable.Columns.Add(
新的DataColumn()
{
数据类型= System.Type.GetType(System.String)//或其他类型的
的ColumnName =名称//或其他列名
}
);

的foreach(查询VAR元素)
{
无功行= MyDataTable.NewRow();
行[名称] = element.NewObject;
myDataTable.Rows.Add(行);
}


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?)

解决方案

Since the query returns an IEnumerable of Type DataRow, you have to specify what to insert into the datatable, in this case 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

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);
}

这篇关于填补LINQ查询的数据表的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆