Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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());
like image 904
Bo Yee Woods Avatar asked May 21 '18 10:05

Bo Yee Woods


1 Answers

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

like image 171
dev-masih Avatar answered Oct 17 '22 06:10

dev-masih