c# - Linq query to dictionary throws System.ArgumentException: An item with the same key has already been added -
this question has answer here:
- c# linq .todictionary() key exists 3 answers
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
Post a Comment