我想将linq查询结果转换为datatable,以便我可以将数据表分配给GridView以在asp页面上显示它.
但是我无法将结果转换为datatable,我没有在我的代码中获取CopyToTable()方法.
请告诉我这里做错了什么?
var gradeData = (from data in oAngieCtxt.prc_ShopInstanceCustomersData(Convert.ToInt32(this.ShopInstanceID), 10000, false) .Where( row => row.RecievedPoints != "n/a" ) .GroupBy(row => new { row.Name }) .Select(g => new GroupedPoints() { Name = g.Key.Name, TotalPoints = g.Sum(x => Convert.ToDouble(x.RecievedPoints) * (x.Weightage.ToString() == "0.00" ? 1 : Convert.ToDouble(x.Weightage))) }) select data).ToList(); DataTable dt = gradeData --gradeData.CopyToTable()
注意:可以使用对dataextentions dll的引用.
提前致谢
你应该得到DataTableExtensions.CopyToDataTable
删除ToList()
.
CopyToDataTable是一个IEnumerable
扩展(不幸的是).
下面有一个自定义CopyToDataTable扩展方法的解决方案.
var gradeData = (from data in oAngieCtxt.prc_ShopInstanceCustomersData( Convert.ToInt32(this.ShopInstanceID), 10000, false) .Where( row => row.RecievedPoints != "n/a" ) .GroupBy(row => new { row.Name }) .Select(g => new { Name = g.Key.Name, TotalPoints = g.Sum(x => Convert.ToDouble(x.RecievedPoints) * (x.Weightage.ToString() == "0.00" ? 1 : Convert.ToDouble(x.Weightage))) }) select data); var dt = gradeData.CopyToDataTable();
编辑:
这是CopyToDataTable的一个更有用的实现DataRow没有类型约束.
public static class DataSetLinqOperators { public static DataTable CopyToDataTable(this IEnumerable source) { //you find the ObjectShredder implementation on the blog wich was linked. return new ObjectShredder ().Shred(source, null, null); } public static DataTable CopyToDataTable (this IEnumerable source, DataTable table, LoadOption? options) { return new ObjectShredder ().Shred(source, table, options); } }