迭代列表列表?
我有来自某个来源的项目(来自其他地方):
public class ItemsFromSource{ public ItemsFromSource(string name){ this.SourceName = name; Items = new List(); } public string SourceName; public List Items; }
现在在MyClass中,我有来自多个来源的项目(从其他地方填充):
public class MyClass{ public MyClass(){ } public List BunchOfItems; }
有没有一种简单的方法可以一次遍历BunchOfItems中所有ItemsFromSources中的所有Items? 即,像:
foreach(IItem i in BunchOfItems.AllItems()){ // do something with i }
而不是做
foreach(ItemsFromSource ifs in BunchOffItems){ foreach(IItem i in ifs){ //do something with i } }
那么,您可以使用linq函数SelectMany进行flatmap (创建子列表并将它们压缩成一个)的值:
foreach(var i in BunchOfItems.SelectMany(k => k.Items)) {}
您可以使用SelectMany
:
foreach(IItem i in BunchOffItems.SelectMany(s => s.Items)){ // do something with i }
你可以为你做一个function。
Enumerable magic(List> lists) { foreach (List list in lists) { foreach (T item in list) { yield return item; } } }
那你就做:
List> integers = ...; foreach (int i in magic(integers)) { ... }
此外,我认为PowerCollections将提供开箱即用的东西。
//Used to flatten hierarchical lists public static IEnumerable Flatten (this IEnumerable items, Func> childSelector) { if (items == null) return Enumerable.Empty (); return items.Concat(items.SelectMany(i => childSelector(i).Flatten(childSelector))); }
我认为这对你想做的事情有用。 干杯。