asp.net – 将linq查询结果转换为datatable C#

前端之家收集整理的这篇文章主要介绍了asp.net – 将linq查询结果转换为datatable C#前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
我想将 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);
    }

  }
原文链接:https://www.f2er.com/aspnet/249172.html

猜你在找的asp.Net相关文章