I have following codes, which causes System.ArgumentException
:
An item with the same key has already been added. Key:PH
_HotelsByCountry = db.Hotels
.GroupBy(hotel => hotel.CountryCode)
.ToDictionary(group => group.Key, group => group.ToList());
Does it mean group key is not unique when use GroupBy
operation?
Update hotel.CountryCode
is type of string
.
Update CountryCode
is foreign key.
Update sql server and ef core 2.0
Update the following code works
_HotelsByCountry = db.Hotels
.GroupBy(hotel => hotel.CountryCode.Trim())
.ToDictionary(group => group.Key, group => group.ToList());
You can Use ToLookup Instead
var x = db.Hotels.ToLookup(hotel => hotel.CountryCode);
For those how wants to know code behind ToLookup
you can check Microsoft Github repo
Basically ToLookup
uses EqualityComparer<TKey>.Default
to compare keys and do what you should do manually when using group by and to dictionary.
I'm not sure, but linqpad not show any sign of converting ToLookup to SQL query so i think it's excuted inmemory
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