Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why do I get a "key already added" error when using the key from a GroupBy in ToDictionary?

Tags:

c#

linq

I had thought that a Linq GroupBy would always produce unique keys, and yet when I project the results of a GroupBy into a Dictionary using .ToDictionary(), I get an error saying "an item with the same key has already been added":

enter image description here

Here's the code in question:

return DbContext.Responsibilities
    .GroupBy(r => r.RoleCode)
    .ToDictionary(g => g.Key, g => g.Count());

[Here Responsibilities is a DbSet of entities whose RoleCode member is a simple int property.]

If I change this to produce a sequence of anonymous types, and then create a dictionary from that, it runs without error:

return DbContext.Responsibilities
    .GroupBy(r => r.RoleCode)
    .Select(g => new { Code = g.Key, Count = g.Count() })
    .ToDictionary(i => i.Code, i => i.Count);

Why does that make such a difference?

FYI, if I create a temporary List variable to hold the anonymous types, here's what the values are:

enter image description here

So, no duplicate keys.

like image 561
Gary McGill Avatar asked Nov 22 '19 11:11

Gary McGill


1 Answers

A simple Google search led me to this blog post:

http://code-ninja.org/blog/2014/07/24/entity-framework-never-call-groupby-todictionary/

The simple answer is that ToDictionary doesn't translate into an Entity Framework query, but it enumerates the result from Group By.

like image 181
Gorgi Rankovski Avatar answered Nov 10 '22 18:11

Gorgi Rankovski