Tutorial :linq aggregate



Question:

class Category  {              public string Name { get; set; }      public int Count { get; set;}  }      Name Count  AA   2  BB   3  AA   4  

I have an IEnumerable<Category>

and would like to get a list of Categories with unique names and the sum of multiple entries

Output

Name Count  AA   6  BB   3  

Update

class Category   {   public string Name { get; set; }   public int CountA { get; set;}   public int CountB { get; set;}   public string Phone { get; set;}   }  

How would I sum two columns. and the phone column can be the last row or any row


Solution:1

var foo = new List<Category>() {                   new Category() { Name = "AA", Count = 2},                  new Category() { Name = "BB", Count = 3},                  new Category() { Name = "AA", Count = 4}              };                var bar = foo.GroupBy(c => c.Name).Select(g => new Category(){ Name = g.Key, Count = g.Sum(c => c.Count) });  


Solution:2

Your updated question isn't entirely clear in terms of the phone number, but I suspect you want something like:

    var query = from category in list                  group category by category.Name into grouped                  select new { Name = grouped.Key,                               SumA = grouped.Sum(x => x.CountA),                               SumB = grouped.Sum(x => x.CountB),                               Phone = grouped.Last().Phone };  

Changing grouped.Last() to grouped.First() would be more efficient, by the way.

Evaluating multiple aggregates in this way isn't terribly efficient in general. The Push LINQ project developed by myself and Marc Gravell makes it a lot more efficient at the cost of not being quite as easy to use. You might want to look into it if you need to deal with a lot of data.


Note:If u also have question or solution just comment us below or mail us on toontricks1994@gmail.com
Previous
Next Post »