将 LINQ 查询转换为动态 Linq
本文关键字:动态 Linq 转换 LINQ 查询 | 更新日期: 2023-09-27 18:32:07
>我有一个看起来像这样的函数:
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>();
}
关于我下一步需要做什么的任何想法?
这个
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);
这应该让你走上正轨吗?