how to get a SUM in Linq?

后端 未结 3 2187
旧巷少年郎
旧巷少年郎 2020-12-06 01:17

I need to do the following, I have a List with a class which contains 2 integer id and count

Now I want to do the following linq query:

         


        
相关标签:
3条回答
  • 2020-12-06 02:03

    Group the items by Id and then sum the Counts in each group:

    var result = items.GroupBy(x => x.Id)
                      .Select(g => new { Id = g.Key, Sum = g.Sum(x => x.Count) });
    
    0 讨论(0)
  • 2020-12-06 02:05

    Try it ,

     .GroupBy(x => x.id)
     .Select(n => n.Sum(m => m.count));
    
    0 讨论(0)
  • 2020-12-06 02:06

    The following program...

    struct Item {
        public int Id;
        public int Count;
    }
    
    class Program {
    
        static void Main(string[] args) {
    
            var items = new [] {
                new Item { Id = 1, Count = 12 },
                new Item { Id = 2, Count = 1 },
                new Item { Id = 1, Count = 2 }
            };
    
            var results =
                from item in items
                group item by item.Id
                into g
                select new { Id = g.Key, Count = g.Sum(item => item.Count) };
    
            foreach (var result in results) {
                Console.Write(result.Id);
                Console.Write("\t");
                Console.WriteLine(result.Count);
            }
    
        }
    
    }
    

    ...prints:

    1       14
    2       1
    
    0 讨论(0)
提交回复
热议问题