Summarize list by property

前端 未结 3 1524
小鲜肉
小鲜肉 2021-01-27 16:48

I have a list of objects like this:

List list = new List();
list.Add(new ClassName()
{
    Name = 1,
    Amount = 5
});
list.Ad         


        
相关标签:
3条回答
  • 2021-01-27 17:00
     var lst = list.GroupBy(g = > g.Name).Select(t = > new
     ClassName()
     {
         Amount = t.Sum(s=>s.Amount), Name = t.Key
     }).ToList();
    
    0 讨论(0)
  • 2021-01-27 17:18

    Do it via LINQ:

    var result = list.GroupBy(x => x.Name)
        .Select(x => new ClassName { Name = x.Key, Amount = x.Sum(i => i.Amount) })
        .ToList();
    

    Read more about LINQ here: http://code.msdn.microsoft.com/101-LINQ-Samples-3fb9811b

    0 讨论(0)
  • 2021-01-27 17:18
    var result = list.GroupBy(x => x.Name).Select(x => new MyClass() {Name=x.Key, Amount= x.Sum(y => y.Amount));
    

    OR

    List<MyClass> result = list.GroupBy(x => x.Name).Select(x => new MyClass() {Name=x.Key, Amount= x.Sum(y => y.Amount)).ToList();
    
    0 讨论(0)
提交回复
热议问题