I have following codes, which causes
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
hotel.CountryCode is type of
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
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