Iterating through a list of lists?

I have items from a specific source (filled out from somewhere else):

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

Now in MyClass I have elements from several sources (filled from another place):

 public class MyClass{ public MyClass(){ } public List<ItemsFromSource> BunchOfItems; } 

Is there an easy way to iterate over all the elements in all the ItemsFromSources elements in BunchOfItems at a time? i.e. something like:

 foreach(IItem i in BunchOfItems.AllItems()){ // do something with i } 

instead of doing

 foreach(ItemsFromSource ifs in BunchOffItems){ foreach(IItem i in ifs){ //do something with i } } 
+6
list c # functional-programming silverlight
source share
4 answers

Well, you can use the linq SelectMany function to layout (create child lists and compress them into one) values:

 foreach(var i in BunchOfItems.SelectMany(k => k.Items)) {} 
+12
source share

You can use SelectMany :

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

You can make a function for this.

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

Then you just do:

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

Also, I think PowerCollections will have something for this out of the box.

+3
source share
  //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))); } 

I think this will work for what you want to do. Greetings.

0
source share

All Articles