C# UWP从IEnumerable中的嵌套列表获取值
我有一个包含嵌套“部分”列表的列表,如下所示:C# UWP从IEnumerable中的嵌套列表获取值,c#,ienumerable,C#,Ienumerable,我有一个包含嵌套“部分”列表的列表,如下所示: private static IEnumerable<Section> Menu() { return new List<Section>() { new Section() { Name = "S1", Submenu = new List<Sec
private static IEnumerable<Section> Menu()
{
return new List<Section>()
{
new Section()
{
Name = "S1",
Submenu = new List<Section>()
{
new Section()
{
Name="S1A",
},
new Section()
{
Name="S1B",
Submenu = new List<Section>()
{
new Section()
{
Name = "S1BA",
},
new Section()
{
Name = "S1BB",
},
new Section()
{
Name = "S1BC",
}
}
},
new Section()
{
Name="S1C",
},
new Section()
{
Name="S1D",
},
}
},
new Section()
{
Name = "S2",
Submenu = new List<Section>()
{
new Section()
{
Name = "S2A",
},
new Section()
{
Name = "S2B",
}
}
},
new Section()
{
Name = "S3"
},
};
}
问题是,当我将其更改为以下内容时:
string sectionName = "S1BC"
Section _section = Menu().First(u => u.Name == sectionName);
我收到一个错误,说什么也没找到
有没有办法做到这一点,或者我的做法是错误的
非常感谢 听起来你想递归地迭代你的分区树?您可以通过简单的深度优先搜索来实现这一点:
private static IEnumerable<Section> Flatten(IEnumerable<Section> sections)
{
foreach (var section in sections)
{
// Yield the section itself
yield return section;
// Visit the section's subsections, and yield them all
if (section.Submenu != null)
{
foreach (var subsection in Flatten(section.Submenu))
{
yield return subsection;
}
}
}
}
private static IEnumerable<Section> Flatten(IEnumerable<Section> sections)
{
foreach (var section in sections)
{
// Yield the section itself
yield return section;
// Visit the section's subsections, and yield them all
if (section.Submenu != null)
{
foreach (var subsection in Flatten(section.Submenu))
{
yield return subsection;
}
}
}
}
string sectionName = "S1BC"
Section _section = Flatten(Menu()).First(u => u.Name == sectionName);