1

I have a class called Component with following properties:

public class Component
{
    public string VerticalType {get; set;}
    public string ProductCode {get; set;}
}

And I have a list:

public List<Component> ComponentList;

and say have following items in it the list:

Internet   54896
TV         24859
Video      48596
Internet   35969

I have a Dictionary and I want to fill it with VerticalType as key and Count as Value. So my dictionary would look like this:

(Internet,2)
(TV,1)
(Video,1)

I am trying something like this but have no clue how to get the count.

var results = lead.SelectedOffer.ComponentList.GroupBy(
     p => p.VerticalType,
     p => p.VerticalTypeCount,
     (key, g) => new { VerticalType = key, Count =  });
Huma Ali
  • 1,759
  • 7
  • 40
  • 66

1 Answers1

2

To get the count in a group, you use the Count() method:

Count = g.Count()

On another note, since all you want is a mapping from VerticalType to the count then I'd suggest going for:

lead.SelectedOffer.ComponentList.GroupBy(p => p.VerticalType)
                  .ToDictionary(g => g.Key, g => g.Count());

or if you want to persist with the IEnumerable of the anonymous types then you still don't need this specific overload of GroupBy you're using in your example code but rather this overload:

lead.SelectedOffer.ComponentList.GroupBy(p => p.VerticalType)
                  .Select(g => new { VerticalType = g.Key, Count = g.Count() });
Ousmane D.
  • 54,915
  • 8
  • 91
  • 126