gpt4 book ai didi

c# - Linq:将 GroupBy 结果传递给函数

转载 作者:行者123 更新时间:2023-12-05 05:39:56 24 4
gpt4 key购买 nike

我需要对列表中的项目进行分组,然后将每个组传递给一个函数以供进一步细化。这是我的代码:

var list = new List<MyObj>(); // list is created ad populated elsewhere in code...

var query = list.AsEnumerable();

query = query.Where(x => x.MyProp == true).Select(x => x); // query definition is way more complicated

var grp = query.GroupBy(x => new { x.Name, x.Surname }).ToList();

在这里grp类型为 List<IGrouping<'a, MyObj>> .

我可以轻松地遍历我的项目:

foreach (var g in grp)
{
foreach (var o in g)
{
// here "o" is of type MyObj
}
}

但我不知道如何创建一个接收组并遍历其项目的函数:

foreach (var g in grp)
{
DoSomethingWithGroup(g);
}

这是因为我在grp定义中有一个匿名类型(Key)。

我尝试用自定义类型替换 Key 匿名类型:

private class GrpKey
{
public string Name { get; set; }
public string Surname { get; set; }
}

/* ... */

var grp = query.GroupBy(x => new GrpKey { Name = x.Name, Surname = x.Surname }).ToList();

这样grp的类型是List<IGrouping<MyGrpKey, MyObj>>而不是 List<IGrouping<'a, MyObj>> .

然后我可以创建一个函数:

private void DoSomethingWithGroup(IGrouping<MyGrpKey, MyObj>) { /* ... */ }

不幸的是,这种分组方式不再有效:grp 现在包含与源列表中的项目一样多的组,每个组都有一个项目。

最佳答案

而不是像你那样指定你的方法:

private void DoSomethingWithGroup(IGrouping<MyGrpKey, MyObj>) 

将键和元素分离到它们的 on 参数中

private void DoSomethingWithGroup<T>(T groupKey, IEnumerable<MyObj> entities)

通过此更改,您可以执行以下操作:

//Populate list with some dummy data
var list = new List<MyObj>()
{
new MyObj { Id = 1, MyProp = true, Name = "A", Surname = "B"},
new MyObj { Id = 2, MyProp = false, Name = "A", Surname = "B"},
new MyObj { Id = 3, MyProp = true, Name = "B", Surname = "B"},
new MyObj { Id = 4, MyProp = true, Name = "B", Surname = "B"},
new MyObj { Id = 5, MyProp = true, Name = "C", Surname = "B"},
};

//Perform the grouping
var groups = list
.Where(x => x.MyProp)
.GroupBy(x => new { x.Name, x.Surname })
.ToList();

//Perform some arbitrary action on the group basis
foreach (var group in groups)
{
DoSomethingWithGroup(group.Key, group);
}

如果 DoSomethignWithGroup 的实现如下所示:

void DoSomethingWithGroup<T>(T groupKey, IEnumerable<MyObj> entities)
{
Console.WriteLine(groupKey);
foreach (var entity in entities)
{
Console.WriteLine($"- {entity.Id}");
}
}

那么输出将是这样的:

{ Name = A, Surname = B }
- 1
{ Name = B, Surname = B }
- 3
- 4
{ Name = C, Surname = B }
- 5

DotnetFiddle link

关于c# - Linq:将 GroupBy 结果传递给函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/72556090/

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