Linq group key is not unique

c# ef-core-2.0 entity-framework-core linq

Question

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());
1
9
5/21/2018 12:59:39 PM

Popular Answer

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

2
5/24/2018 12:02:04 PM


Related Questions





Related

Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow
Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow