Bo Yee Woods
Bo Yee Woods

Reputation: 136

Linq group key is not unique

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());

Upvotes: 9

Views: 442

Answers (1)

dev-masih
dev-masih

Reputation: 4746

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

Upvotes: 2

Related Questions