遍历列表列表? [英] 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;
}
现在在 MyClass 中,我有来自多个来源的项目(从其他地方填充):
Now in MyClass I have Items from several sources (populated from somewhere else):
public class MyClass{
public MyClass(){
}
public List<ItemsFromSource> BunchOfItems;
}
有没有一种简单的方法可以一次性遍历 BunchOfItems 中所有 ItemsFromSources 中的所有 Item?即,类似于:
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
}
而不是做
foreach(ItemsFromSource ifs in BunchOffItems){
foreach(IItem i in ifs){
//do something with i
}
}
推荐答案
好吧,你可以使用 linq 函数 SelectMany 来flatmap(创建子列表并将它们压缩为一个)值:>
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)) {}
这篇关于遍历列表列表?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文