English 中文(简体)
通过名单?
原标题:Iterating through a list of lists?

我从某种来源获得物品(从其他地点收集):

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

    public string SourceName;
    public List<IItem> Items;
}

现在,MyClass 我从几个来源获得物品(从其他地方收集):

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
}

不这样做

foreach(ItemsFromSource ifs in BunchOffItems){
    foreach(IItem i in ifs){
        //do something with i
    }
}
最佳回答

您也可使用Lexq功能选择Many到flatmap。 价值观:

foreach(var i in BunchOfItems.SelectMany(k => k.Items)) {}
问题回答

http://msdn.microsoft.com/en-us/library/bb534336.aspx”rel=“noreferer”SelectMany:

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

你们可以发挥这种作用。

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

之后,你刚刚做到:

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

另外,我想PowerCollections将从盒子中选取一些东西。

    //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)));
    }

我认为,这将有利于你想要做的工作。 乘客。





相关问题
Anyone feel like passing it forward?

I m the only developer in my company, and am getting along well as an autodidact, but I know I m missing out on the education one gets from working with and having code reviewed by more senior devs. ...

NSArray s, Primitive types and Boxing Oh My!

I m pretty new to the Objective-C world and I have a long history with .net/C# so naturally I m inclined to use my C# wits. Now here s the question: I feel really inclined to create some type of ...

C# Marshal / Pinvoke CBitmap?

I cannot figure out how to marshal a C++ CBitmap to a C# Bitmap or Image class. My import looks like this: [DllImport(@"test.dll", CharSet = CharSet.Unicode)] public static extern IntPtr ...

How to Use Ghostscript DLL to convert PDF to PDF/A

How to user GhostScript DLL to convert PDF to PDF/A. I know I kind of have to call the exported function of gsdll32.dll whose name is gsapi_init_with_args, but how do i pass the right arguments? BTW, ...

Linqy no matchy

Maybe it s something I m doing wrong. I m just learning Linq because I m bored. And so far so good. I made a little program and it basically just outputs all matches (foreach) into a label control. ...

热门标签