0

I have something like this:

var result = new MyList()
{
    Items = new List<Item>(),
    ...
}

where each Item has, among others, an itemType property, I need a Dictionary<itemType, count> which returns the count of each itemType in my list. I did this:

var res = new Dictionary<itemType, int>();
res = result.Items.ToDictionary(a => a.itemType,
                                a=> result.Items.Count(i => i.itemType== a.itemType));}

But I'm getting this error "An item with the same key has already been added" beacuse of course there are several items with the same type in my list, how can I do a group by or a distinct???

puretppc
  • 3,232
  • 8
  • 38
  • 65
ety
  • 75
  • 1
  • 10

1 Answers1

1

You can shorten it, but anyway:

var groups = result.Items.GroupBy(r => r.itemType).Select(g => new { id = g.Key, count = g.Count() });
var res = new Dictionary<itemType, int>();
res = groups.ToDictionary(a => a.id, a=>a.count);
Lowkey
  • 836
  • 5
  • 12