LINQ查询结果转换为数据表C# [英] convert linq query results to datatable C#
问题描述
我要转换的LINQ查询结果以数据表,这样我可以分配到数据表GridView控件来显示它的ASP页面上。
I want to convert the linq query results to datatable so that I can assign datatable to GridView to show it on asp page.
但是我不能够将结果转换为数据表,我没有得到CopyToTable()方法,在我的code。
However I am not able to convert the results to datatable, I am not getting CopyToTable() method in my code.
请指教一下我做错了吗?
please advise what am I doing wrong here?
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可用
Note: reference to dataextentions dll is available.
在此先感谢
推荐答案
您应该得到的 DataTableExtensions.CopyToDataTable
删除了ToList()
。
CopyToDataTable是的IEnumerable< DataRow的方式>
扩展(不幸)
CopyToDataTable is an IEnumerable<DataRow>
extension (unfortunately).
有与下面的自定义CopyToDataTable扩展方法解决方案。
There is a solution with custom CopyToDataTable extension method below.
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。
Here is a more useful implementation of CopyToDataTable There is no type constraint to DataRow.
public static class DataSetLinqOperators
{
public static DataTable CopyToDataTable<T>(this IEnumerable<T> source)
{
//you find the ObjectShredder implementation on the blog wich was linked.
return new ObjectShredder<T>().Shred(source, null, null);
}
public static DataTable CopyToDataTable<T>(this IEnumerable<T> source,
DataTable table, LoadOption? options)
{
return new ObjectShredder<T>().Shred(source, table, options);
}
}
这篇关于LINQ查询结果转换为数据表C#的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!