2009-11-20 222 views
6

我有一定的来源(从别的地方居住)的项目:遍历列表的列表?

public class ItemsFromSource{ 
    public ItemsFromSource(string name){ 
     this.SourceName = name; 
     Items = new List<IItem>(); 
    } 

    public string SourceName; 
    public List<IItem> Items; 
} 

现在MyClass中我有几个来源的项目(从别的地方居住):

public class MyClass{ 
    public MyClass(){ 
    } 

    public List<ItemsFromSource> 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 
    } 
} 
+0

如果ItemsFromSource ISA的iItem比你的第一的foreach会工作,否则也不会工作。 – Woot4Moo 2009-11-20 17:03:36

+0

我想你应该说明你正在使用的.NET版本,因为有些人正在提供LINQ作为选项,并不适用于所有版本的.NET。 – 2009-11-20 17:13:54

回答

12

好了,你可以使用LINQ功能的SelectMany到flatmap(创建子列表,并将它们压缩成一个)值:

foreach(var i in BunchOfItems.SelectMany(k => k.Items)) {} 
3

你可以做一个函数来为你做的。

Enumerable<T> magic(List<List<T>> lists) { 
    foreach (List<T> list in lists) { 
    foreach (T item in list) { 
     yield return item; 
    } 
    } 
} 

然后你只需要做:

List<List<int>> integers = ...; 
foreach (int i in magic(integers)) { 
    ... 
} 

另外,我觉得PowerCollections将有一些对于开箱。

0
//Used to flatten hierarchical lists 
    public static IEnumerable<T> Flatten<T>(this IEnumerable<T> items, Func<T, IEnumerable<T>> childSelector) 
    { 
     if (items == null) return Enumerable.Empty<T>(); 
     return items.Concat(items.SelectMany(i => childSelector(i).Flatten(childSelector))); 
    } 

我认为这会为你想要的东西的工作做。干杯。

5

您可以使用SelectMany

foreach(IItem i in BunchOffItems.SelectMany(s => s.Items)){ 
    // do something with i 
}