2

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! :)

4

2 回答 2

2

首先检查您的 id 是否唯一。要在字典中添加内容,您需要唯一的键。我认为您的密钥不是唯一的。如果 internalID 在您的数据库中是唯一的,则编写下面给出的以下代码。

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);
于 2013-04-24T06:05:47.913 回答
0

尝试这个:

var randomDict = db.tbl_generatedsampledetails
                   .Where(detail => detail.genID == id)
                   .Select(detail => new { detail.internalID, detail.@operator })
                   .ToDictionary(det => det.internalID,
                                 det => det.@operator);
于 2013-04-24T06:13:12.750 回答