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":
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:
So, no duplicate keys.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With