UWP 从 IEnumerable 中的嵌套列表中获取值
UWP get values from nested List in IEnumerable
我有这样的带有“部分”嵌套列表的列表:
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 = "S1"
Section _section = Menu().First(u => u.Name == sectionName);
问题是,当我将其更改为类似以下内容时:
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;
}
}
}
}
然后您可以使用它来获取所有部分的扁平化列表,并在其中搜索您要查找的部分
string sectionName = "S1BC"
Section _section = Flatten(Menu()).First(u => u.Name == sectionName);
我有这样的带有“部分”嵌套列表的列表:
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 = "S1"
Section _section = Menu().First(u => u.Name == sectionName);
问题是,当我将其更改为类似以下内容时:
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;
}
}
}
}
然后您可以使用它来获取所有部分的扁平化列表,并在其中搜索您要查找的部分
string sectionName = "S1BC"
Section _section = Flatten(Menu()).First(u => u.Name == sectionName);