gpt4 book ai didi

c# - 如果在嵌套集合上使用 SelectMany,则保留父实例

转载 作者:行者123 更新时间:2023-11-30 19:15:04 26 4
gpt4 key购买 nike

我有一个模型Person的集合:

class Person
{
public string FirstName {get; set;}
public string LastName {get; set;}
public string Company {get; set;}
public IEnumerable<string> Tags {get; set;}
}

并会通过 LINQ 将这个集合转换为另一个按标签分组的集合。我该怎么做?

到目前为止我的方法:

var result = PersonCollection
.SelectMany(m => m.Tags)
.GroupBy(b => b);

但这会丢弃有关此人的所有信息。

最佳答案

您可以将 Person 持久化为匿名类型:

var result = PersonCollection
.SelectMany(p => p.Tags.Select(t => new{ Person = p, Tag = t }))
.GroupBy(x => x.Tag);

现在这些组仍然包含标签作为键和人员:

foreach (var tagPersons in result)
{
Console.WriteLine($"Tag: {tagPersons.Key}");
Console.Write($" all persons: {string.Join(",", tagPersons.Select(x => x.Person.LastName))}");
}

关于c# - 如果在嵌套集合上使用 SelectMany,则保留父实例,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47651530/

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