我有一个有孩子[同一类型]的人员名单.我从xml文件中获取列表.
场景:
人:身份证,姓名,性别,年龄,儿童[有关领域的类]
如果personList有1,2,5个Ids,
2和5分别有3,4和6,7,8.
我必须得到最大id为8.
如何使用lambda表达式从PersonList获取Id的最大值?
你可以尝试组合Concat和SelectMany(假设它只是嵌套的一个级别):
var maxId = personList.Concat(personList.SelectMany(p => p.Children)).Max(p => p.Id);
Run Code Online (Sandbox Code Playgroud)
更新
如果您有多个嵌套级别,您还可以编写一个扩展方法来进行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;
}
}
}
Run Code Online (Sandbox Code Playgroud)
这不会处理循环引用,它的行为也不同于SelectMany返回源集合本身中的项目(因此您可能想要更改名称),但我认为它可以完成这项工作.你可以很容易地使用它:
var maxId = personList.SelectManyRecursive(p => p.Children).Max(p => p.Id);
Run Code Online (Sandbox Code Playgroud)