gpt4 book ai didi

c# - 从具有相同列表子项的列表中查找最大 ID

转载 作者:太空宇宙 更新时间:2023-11-03 20:25:13 24 4
gpt4 key购买 nike

我有一个有 child [相同类型]的人的列表。我从 xml 文件中获取列表。

场景:

Person : Id, Name, Gender, Age, Children [Class with fields]

如果personList有1,2,5个Id,
2 岁和 5 岁分别有 3、4 岁和 6、7、8 岁的 child 。
我必须将最大 ID 设置为 8。

我如何使用 lambda 表达式从 PersonList 中获取 Id 的最大值?

最佳答案

您可以尝试 Concat 的组合和 SelectMany (假设它只嵌套了一层):

var maxId = personList.Concat(personList.SelectMany(p => p.Children)).Max(p => p.Id);

更新
如果您有多个嵌套级别,您还可以编写一个扩展方法来使 SelectMany 递归:

public static IEnumerable<T> SelectManyRecursive<T>(this IEnumerable<T> source, Func<T, IEnumerable<T>> selector) {
if (source == null) { yield break; }
foreach (var item in source) {
yield return item;
foreach (var selected in selector(item).SelectManyRecursive(selector)) {
yield return selected;
}
}
}

它不处理循环引用,它的行为与 SelectMany 不同,它还返回源集合本身中的项目(因此您可能想更改名称),但除此之外我认为它确实如此工作。你可以很容易地使用它:

var maxId = personList.SelectManyRecursive(p => p.Children).Max(p => p.Id);

关于c# - 从具有相同列表子项的列表中查找最大 ID,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10992157/

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