代码之家  ›  专栏  ›  技术社区  ›  Graviton

如何将元素列表附加到另一个列表中

  •  6
  • Graviton  · 技术社区  · 15 年前

    我有下面的课

    public class Element
    {
      public List<int> Ints
      {
         get;private set;
      }
    }
    

    给定一个 List<Element> ,如何查找 Ints 里面 列表<元素> 使用LINQ?

    我可以用下面的代码

    public static List<int> FindInts(List<Element> elements)
    {
     var ints = new List<int>();
     foreach(var element in elements)
     {
      ints.AddRange(element.Ints);
     }
     return ints;
     }
    }
    

    但它是如此的丑陋和长篇大论,我想呕吐每一次我写它。

    有什么想法吗?

    3 回复  |  直到 15 年前
        1
  •  10
  •   Marc Gravell    15 年前
    return (from el in elements
            from i in el.Ints
            select i).ToList();
    

    或者也许只是:

    return new List<int>(elements.SelectMany(el => el.Ints));
    

    顺便说一句,您可能需要初始化列表:

    public Element() {
        Ints = new List<int>();
    }
    
        2
  •  3
  •   Christian C. Salvadó    15 年前

    你可以简单地使用 SelectMany 把它压平 List<int> :

    public static List<int> FindInts(List<Element> elements)
    {
        return elements.SelectMany(e => e.Ints).ToList();
    }
    
        3
  •  0
  •   Rafa Castaneda    15 年前

    …或聚合:

    List<Elements> elements = ... // Populate    
    List<int> intsList = elements.Aggregate(Enumerable.Empty<int>(), (ints, elem) => ints.Concat(elem.Ints)).ToList();