Dynamic Linq:选择已知类型的新对象

时间:2017-06-20 07:53:51

标签: c# linq dynamic-linq

考虑我们有这个用于聚合报告的类:

public class ReportSeriesData
{
    public string Title { get; set; }
    public double Value { get; set; }

    public ReportSeriesData()
    {

    }

    public ReportSeriesData(string Title, double Value)
    {

    }
}

我使用Dynamic Linq对记录进行分组,然后我想将结果选择到ReportSeriesData列表中

  var reportData = list.AsQueryable().GroupBy(UserSelectedField, "it").Select("new (it.Key as Title, it.Count() as Value) as ReportSeriesData");

上述语句产生错误:

  

发生了'System.Linq.Dynamic.ParseException'类型的异常   System.Linq.Dynamic.dll但未在用户代码中处理

     

其他信息:语法错误

在动态linq中选择已知类型对象的正确方法是什么?

1 个答案:

答案 0 :(得分:-1)

你可以这样做

var reportData = from instance in list  
group instance by instance.UserSelectedField into group  
select new ReportSeriesData() with {.Title = group.Key,.Value = group.Count}

  var reportData=list.AsQueryable().GroupBy(UserSelectedField, "it").Select(g => new ReportSeriesData() 
    { 
        Title= g.Key,
        Value= g.Count
    }