c# - Linq query to dictionary throws System.ArgumentException: An item with the same key has already been added -


this question has answer here:

i have following linq query using query datatable , populate dictionary, keeps throwing error:

system.argumentexception: item same key has been added.

i new linq , cannot figure out proper way write this.

can please assist?

var newordergroupdict = (from m in kmvdata.asenumerable()                          select new                          {                            datakey = m.field<string>("ordernumber"),                            datavalue = m.field<int>("ordergroup")                          }).distinct().todictionary(n => n.datakey, n => n.datavalue); 

that means data key (in case combination of ordernumber , ordergroup) not unique. happens because .distinct() wont filter duplicates without iequalitycomparer type.

edit:

one way of fixing , preserving datavalues ordernumber first grouping , converting dictionary:

var newordergroupdict = (from m in kmvdata.asenumerable()                          select new                          {                              datakey = m.field<string>("ordernumber"),                              datavalue = m.field<int>("ordergroup")                          }).groupby(x => x.datakey)                          .todictionary(g => g.key, g => g.tolist()); 

Comments

Popular posts from this blog

user interface - Python attempting to create a simple gui, getting "AttributeError: 'MainMenu' object has no attribute 'intro_screen'" -

jquery - Common JavaScript snippet to share files on Google Drive, Dropbox, Box.net or SkyDrive -

Android Gson.fromJson error -