我有以下课程
public class Element
{
public List<int> Ints
{
get;private set;
}
}
给定List< Element>,如何找到List< Element>内的所有Int的列表.使用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;
}
}
但它是如此丑陋和冗长的啰嗦,我想每次写作都呕吐.
有任何想法吗?
解决方法
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>();
}