我有一个类(classA),它有另一个类(classB)的列表,后者又有另一个类(classC)的列表。我想在ID属性与我正在搜索的内容匹配时检索classC的特定实例。这就是我现在所拥有的:
ClassC foundC = null;
foreach (var a in aList)
{
foreach (var b in a.bList)
{
foreach (var c in b.cList)
{
if (c.IdProperty == searchId)
{
foundC = c;
}
}
}
}
是否可以使用Linq执行此搜索?
答案 0 :(得分:3)
var c = aList
.SelectMany(_ => _.bList)
.SelectMany(_ => _.cList)
.FirstOrDefault(_ => _.IdProperty == searchId);
答案 1 :(得分:3)
var foundC = aList.SelectMany(a => a.bList).SelectMany(b => b.cList).FirstOrDefault(c => c.IdProperty == searchId);
答案 2 :(得分:1)
您可以使用嵌套的SelectMany
s + FirstOrDefault
:
ClassC foundC = aList.SelectMany(a => a.bList.SelectMany(ab => ab.cList))
.FirstOrDefault(c => c.IdProperty == searchId);
if(foundC != null)
{
// found one
}