【问题标题】:Iterating through a list of lists?遍历列表列表?
【发布时间】:2010-12-18 19:33:37
【问题描述】:

我有来自某个来源(从其他地方填充)的项目:

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

有没有一种简单的方法可以一次性遍历 BunchOfItems 中所有 ItemsFromSources 中的所有项目? 即,类似:

foreach(IItem i in BunchOfItems.AllItems()){
    // do something with i
}

而不是做

foreach(ItemsFromSource ifs in BunchOffItems){
    foreach(IItem i in ifs){
        //do something with i
    }
}

【问题讨论】:

  • 如果 ItemsFromSource isA IItem 而不是你的第一个 foreach 将起作用,否则两者都不起作用。
  • 我认为您应该说明您正在使用的 .NET 版本,因为有些人提供 LINQ 作为选项,并非所有版本的 .NET 都可用..

标签: c# silverlight list functional-programming


【解决方案1】:

好吧,你可以使用 linq 函数 SelectMany 来flatmap(创建子列表并将它们压缩为一个)值:

foreach(var i in BunchOfItems.SelectMany(k => k.Items)) {}

【讨论】:

    【解决方案2】:

    你可以使用SelectMany:

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

    【讨论】:

      【解决方案3】:

      你可以为你做一个函数。

      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 会有一些开箱即用的东西。

      【讨论】:

        【解决方案4】:
            //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)));
            }
        

        我认为这将适用于您想要做的事情。干杯。

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 2011-02-16
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2022-01-07
          相关资源
          最近更新 更多