我有一个IEnumerable
集合Car
对象
汽车有一个属性:年份
使用 LINQ,我想找到同一年份有 > 1 辆汽车的位置并返回该列表。
我希望它必须返回一个列表数组,因为如果集合是:
Car 1: Year 2010
Car 2: Year 2010
Car 3: Year 2009
Car 4: Year 2009
Car 5: Year 2010
Car 6: Year 2008
我希望 2010 年有一份 3 人名单,2009 年有一份 2 人名单
这可能吗?
最佳答案
您可以通过分组来做到这一点。参见 hooked on linq更多 sample
var result = from car in cars
group car by car.year into g
where g.Count() > 1
select g
现在结果是 IEnumerable<IGrouping<int, Car>>
,这意味着您可以这样做:
foreach(var g in result)
{
int year = g.Key;
foreach(var car in g)
{
// list the cars
}
}
关于c# - 使用 LINQ 转换 IEnumerable 的集合,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3774068/