将LINQ查询转换为Dynamic Linq

时间:2016-01-27 19:30:03

标签: c# linq dynamic-linq

我有一个看起来像这样的函数:

public void GetAvailableResourcesByLocationChart(List<DateTime> dates, List<ChartResourceModel> data)
{
    var totals = (from r in data
                  group new { Dates = r.Dates } by r.Location into g
                  select new
                  {
                      Location = g.Key,
                      Dates = dates.Select(d => new
                      {
                          Date = d,
                          Available = g.SelectMany(x => x.Dates.Where(y => y.Date == d)).Count(x => x.Available)
                      })
                      .OrderBy(x => x.Date)
                      .ToList()
                  })
                 .OrderBy(x => x.Location)
                 .ToList();
 }

此示例根据位置对数据进行分组。但我希望能够传入一个字符串,指定它应该分组的内容。我认为DynamicLinq是解决这个问题的正确方法,但我很难复制它。

我开始这样做了,但是在选择中复制SelectMany时卡住了:

public void GetAvailableResourcesByLocationChart(List<DateTime> dates, List<ChartResourceModel> data, string grouping)
{
    var totals = data.GroupBy(grouping, "it").Select("new (it.Key as Group, it as Dates)").Cast<dynamic>();
}

关于我接下来需要做什么的任何想法?

1 个答案:

答案 0 :(得分:0)

这个

   from r in data
   group new { Dates = r.Dates } by r.Location into g
   ...

与此相同

   data.GroupBy(r => r.Location, b => b.Dates)

所以如果我们有变量命名的石斑鱼

   data.GroupBy(r => {
      if (grouper == "L") 
        return r.Location 
      else
        return r.Dates }, b => b.Dates);

这会让你走上正轨吗?