gpt4 book ai didi

c# - 如何按多个通用 linq 表达式分组

转载 作者:行者123 更新时间:2023-11-30 16:25:13 24 4
gpt4 key购买 nike

我正在尝试使用 Linq 表达式构建查询,但在尝试按多列分组时遇到困难。假设我有一个基本集合:

IEnumerable<Row> collection = new Row[]
{
new Row() { Col1 = "a", Col2="x" },
new Row() { Col1 = "a", Col2="x" },
new Row() { Col1 = "a", Col2="y" },
};

我知道您可以使用 lambda 表达式对它们进行分组:

foreach (var grp in collection.GroupBy(item => new { item.Col1, item.Col2 }))
{
Debug.Write("Grouping by " + grp.Key.Col1 + " and " + grp.Key.Col2 + ": ");
Debug.WriteLine(grp.Count() + " rows");
}

如您所见,这组正确:

Grouping by a and x: 2 rows
Grouping by a and y: 1 rows

但是现在,假设我收到一组选择器来分组,它作为我方法中的参数传递给我,并且实体类型是通用的:

void doLinq<T>(params Expression<Func<T,object>>[] selectors)
{
// linq stuff
}

调用方法的人会这样调用:

doLinq<Row>(entity=>entity.Col1, entity=>entity.Col2);

我将如何构造分组依据表达式?

foreach (var grp in collection.GroupBy(
item => new {
// selectors??
}))
{
// grp.Key. ??
}

编辑

我在上面进行了更新,希望能阐明为什么我需要这组选择器。

编辑 #2

使 doLinq 中的实体类型通用。

最佳答案

关于c# - 如何按多个通用 linq 表达式分组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10146295/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com