0

I would like to Sum grouped items. I would like to do keep simple LINQ syntax.

What I need to fix in the code to get items for key. I am trying like "g[g.Key].Count()", which doesn't work.

public class Order
{
    public string Id { get; set; }
    public string Name { get; set; }
    public string Group { get; set; }
}

public class Group
{
    public string GroupId { get; set; }
    public string Count { get; set; }
}     


**var groupedOrd = orders.GroupBy(f => f.Group);**
List<Group> groups = new List<Group>();
foreach(var g in groupedOrd)
{
   groups.Add(new Group() { GroupId = g.Key, Count = g[g.Key].Count() });
}

1 Answers1

6

GroupBy returns IEnumerable of IGrouping<TKey,TElement> which implements IEnumerable<T> so you can just do g.Count():

var groups  = groupedOrd
    .Select(g => new Group { GroupId = g.Key, Count = g.Count() } )
    .ToList();

Also your Group.Count property is a string for some reason, so you will need to change it to int or do g.Count().ToString()

Guru Stron
  • 102,774
  • 10
  • 95
  • 132