将 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() 方法.
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()
注意:可以参考dataextensions dll.
Note: reference to dataextentions dll is available.
提前致谢
推荐答案
你应该得到 DataTableExtensions.CopyToDataTable
删除ToList()
.
CopyToDataTable 是一个 IEnumerable
扩展(不幸的是).
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屋!