使用Linq计算ObservableCollection值的总和

时间:2015-05-04 13:33:15

标签: c# linq

这是我的代码示例

class Gold
{
    public String Category { get; set; }
    public Double Weight { get; set; }
}
class Metal
{
    public ObservableCollection<Gold> GoldCollection { get; set; }
    public String Name { get; set; }
    public Double Amount { get; set; }
}
class Collection
{
    public ObservableCollection<Metal> MetalCollection { get; set; }
    public String Category { get; set; }
    public Double TotalWeight { get; set; }
}

如何使用LINQ从Collection模型计算Gold Weight,按类别分组?

2 个答案:

答案 0 :(得分:2)

你走了:

Collection obj = new Collection();

obj.MetalCollection.SelectMany(m => m.GoldCollection).GroupBy(g => g.Category).Select(t => new { t.Key, MySum = t.Sum(n => n.Weight).ToString() });

答案 1 :(得分:0)

那样的东西?

var result = from m in collection.MetalCollection
             from g in m.GoldCollection
             group g by g.Category
             into gg
             select new
             {
                 Category = gg.Key,
                 Sum = gg.Sum(x => x.Weight)
             };
相关问题