在C#中需要有关LINQ lambda表达式的帮助。
因此,让我解释一下我的对象的结构。
RootObject是一个具有许多属性的集合(具有多个属性的自定义类),其中一个属性是List<Item>
项。
项目包含List<Round>
个回合。
回合包含EntryRID
(此ID是唯一的)和name
。
string = IDToFind = "111"; //The ID i want a Round object for
因此,从我的“项目”列表中,我需要找到与给定ID(IDToFind)相匹配的回合ID。
我又需要在“项目”中的每个单项中搜索ID匹配IDToFind的Round对象。
我已经厌倦了这个表情:
Round playerRound = RootObject.Select(i => i.Items.Select(x => x.Rounds.Where(y => y.EntryRID == Int32.Parse(IDToFind))));
但它不返回任何类型的对象,返回的是:
System.Linq.Enumerable+WhereSelectListIterator`2[Leaderboards,System.Collections.Generic.IEnumerable`1[System.Collections.Generic.IEnumerable`1[Round]]]
最佳答案
您的查询为每个IEnumerable
元素返回IEnumerable
的RootObject
。这是因为您的查询会为IEnumerable
的每个项目生成一个RootObject
,并将结果也设为IEnumerable
。
如果要将结果拼合为一个列表,请使用SelectMany
,如下所示:
var matchingItems = RootObject.SelectMany(i => i.Items.SelectMany(x => x.Rounds.Where(y => y.EntryRID == Int32.Parse(IDToFind))));
上面产生了一个可以迭代的集合:
foreach (var item in matchingItems) {
Console.WriteLine(item.ToString();
}