我尝试(使用 LINQ)堆叠相同类型的元素列表,然后增加一个匿名属性..
ElementA
ElementA
ElementB
ElementB
ElementB
ElementC
成为暴露元素和数量的匿名对象..
ElementA (Property Qty = 2)
ElementB (Property Qty = 3)
ElementC (Property Qty = 1)
有没有什么优雅的方法可以用 LINQ 做到这一点?
不确定这是否有效,但绝对有可能。类似的东西
var totals = from e in <element list>
group e by e.<property> into g
select new {
Property = g.Key,
Count = g.Count()
}
会给你一个属性的计数。
在这种情况下g
是 type IGrouping<out TKey, out TElement>
,它继承自IEnumerable<T>
所以它可以做任何IEnumerable<T>
可以做的事情。