C# LINQ:如何将元素列表附加到另一个列表中
我有以下课程C# LINQ:如何将元素列表附加到另一个列表中,c#,linq,C#,Linq,我有以下课程 public class Element { public List<int> Ints { get;private set; } } 但它是如此丑陋和冗长,以至于我每次写它都想呕吐 有什么想法吗 return (from el in elements from i in el.Ints select i).ToList(); 或者只是: return new List<int>(elements.S
public class Element
{
public List<int> Ints
{
get;private set;
}
}
但它是如此丑陋和冗长,以至于我每次写它都想呕吐
有什么想法吗
return (from el in elements
from i in el.Ints
select i).ToList();
或者只是:
return new List<int>(elements.SelectMany(el => el.Ints));
返回新列表(elements.SelectMany(el=>el.int));
顺便说一句,您可能需要初始化列表:
public Element() {
Ints = new List<int>();
}
public元素(){
Ints=新列表();
}
您只需使用选择多个
即可获得一个扁平的列表
:
公共静态列表FindInts(列表元素)
{
返回元素;
}
。。。或聚合:
List<Elements> elements = ... // Populate
List<int> intsList = elements.Aggregate(Enumerable.Empty<int>(), (ints, elem) => ints.Concat(elem.Ints)).ToList();
List元素=…//居住于
List intsList=elements.Aggregate(Enumerable.Empty(),(ints,elem)=>ints.Concat(elem.ints)).ToList();
您使用“新列表(x)”而不是“x.ToList()”有什么原因吗?
public static List<int> FindInts(List<Element> elements)
{
return elements.SelectMany(e => e.Ints).ToList();
}
List<Elements> elements = ... // Populate
List<int> intsList = elements.Aggregate(Enumerable.Empty<int>(), (ints, elem) => ints.Concat(elem.Ints)).ToList();