我想将
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< DataRow>延期(不幸的是).
下面有一个自定义CopyToDataTable扩展方法的解决方案.
var gradeData = (from data in oAngieCtxt.prc_ShopInstanceCustomersData( Convert.ToInt32(this.ShopInstanceID),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<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); } }