finnTheHumin
finnTheHumin

Reputation: 165

C# linq to entity An item with the same key has already been added

I'm trying to query some records from my database and convert the result into a Dictionary with string key and string value but continually gets the error "An item with the same key has already been added.".

this is my linq query:

var random = (from rec in db.tbl_generatedsampledetails
              where rec.genID == id
              select new
              {
                     rec.@operator,
                     rec.internalID
              }).ToDictionary(r => r.@operator, r => r.internalID);

Thanks for the help! :)

Upvotes: 2

Views: 2764

Answers (2)

roybalderama
roybalderama

Reputation: 1640

Try this:

var randomDict = db.tbl_generatedsampledetails
                   .Where(detail => detail.genID == id)
                   .Select(detail => new { detail.internalID, detail.@operator })
                   .ToDictionary(det => det.internalID,
                                 det => det.@operator);

Upvotes: 0

Atish Kumar Dipongkor
Atish Kumar Dipongkor

Reputation: 10422

First of all check your id is unique or no. To add something in a dictionary you need unique key. I think your key is not unique. if internalID is unique in your database then write the following code given bellow.

var random = (from rec in db.tbl_generatedsampledetails
                                                 where rec.genID == id
                                                 select new { rec.@operator, rec.internalID }).ToDictionary(r => r.internalID,r => r.@operator);

Upvotes: 2

Related Questions