Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Iterating through a list of lists?

I have Items from a certain source (populated 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 Items from several sources (populated from somewhere else):

public class MyClass{
    public MyClass(){
    }

    public List<ItemsFromSource> BunchOfItems;
}

Is there a simple way to iterate through all Items in all ItemsFromSources in BunchOfItems in one go? 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
    }
}
like image 548
eriksmith200 Avatar asked Nov 20 '09 17:11

eriksmith200


People also ask

Does Python iterate through list in order?

Yes, it should, every time, since lists are ordered. If you are iterating over a dict , the order may be different than expected. Python dicts are unordered.


2 Answers

You could make a function to do that for you.

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 that out of the box.

like image 105
Aviad Ben Dov Avatar answered Oct 22 '22 00:10

Aviad Ben Dov


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

foreach(var i in BunchOfItems.SelectMany(k => k.Items)) {}
like image 43
Dario Avatar answered Oct 22 '22 01:10

Dario