通过列表的列表迭代? [英] Iterating through a list of lists?
本文介绍了通过列表的列表迭代?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有一定的来源(从别的地方居住)的项目:
公共类ItemsFromSource {
公ItemsFromSource(字符串名称){
this.SourceName =名称;
项=新的List<&的iItem GT;();
}
公共字符串SOURCENAME;
公开名单<&的iItem GT;项目;
}
现在MyClass中我已经从多个来源的项目(从别的地方填充):
公共类MyClass的{
公共MyClass的(){
}
公开名单< ItemsFromSource> BunchOfItems;
}
有没有一种简单的方法,通过在各ItemsFromSources在所有项目中BunchOfItems遍历一气呵成?
即是这样的:
的foreach(的iItem我BunchOfItems.AllItems()){
/ /做一些与我
}
而不是做
的foreach(在BunchOffItems ItemsFromSource IFS){
的foreach(的iItem我IFS){
//做一些与我
}
}
解决方案
好了,你可以使用LINQ的功能的SelectMany到的 flatmap 的(创建子列表和它们压缩成一个)的值:
的foreach(VAR我在BunchOfItems.SelectMany(K => k.Items)){}
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
}
}
解决方案
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屋!
查看全文