在Hierarchy中循环获取每个关卡的第一个元素
本文关键字:第一个 元素 Hierarchy 循环 获取 | 更新日期: 2023-09-27 18:15:56
我有一个类:
public class Member
{ public string header {get;set;}
public List<Member> MemberCollection {get;set;}
}
所以我有List lstMembers;包含如下内容:
MemberA
|_____ header = HeadingMemberA
|
|_____ List<Member> = Member A.1
|___ Member A.2
|___ Member A.3
MemberB
|_____ header = HeadingMemberB
|
|_____ List<Member> = Member B.1
|___ Member B.2
|___ Member B.3
所以现在我必须在每个级别获得第一个成员。
list Member a、Member A.1、Member b、Member B.1
像这样:
List<Member> firstLevels = new List<Member>();
foreach(Member m in lstMembers)
{
firstLevels.Add(m);
firstLevels.Add(m.MemberCollection.First());
}
好吧,Member A
&Member B
不是第一个在他们的水平
但如果想要得到Member A.1, Member B.1 ...
members.Select(MemberList => MemberList.MemberCollection.FirstOrDefault()).ToList();
如果允许使用LINQ,则可以在集合上构建表达式。在order by子句中使用SelectMany操作符
注意:下面的代码只是为了演示思想,忽略任何语法/大小写问题
var members = new List<Member>();
var q = members.SelectMany(m => m.MemberCollection).Orderby(o=>o.Name).FirstOrDefault()
.ToList();