Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

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
    }
}
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
535 views
Welcome To Ask or Share your Answers For Others

1 Answer

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)) {}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...