Lambda/Linq Error "an Item with the same key has already been added"
"An item with the same key has already been added" is the error I'm getting. What am I doing wr开发者_运维技巧ong? Thank you in advance for any help.
using (var Customerconn = new DataClassesDataContext())
{
Dictionary<int, string> Empsource = Customerconn.tblOutOfOfficeLogs
.Join(Customerconn.tblEmployees,
l => l.EmployeeID,
emp => emp.EmployeeID,
(l, emp) => new { ID = emp.EmployeeID, Name = emp.FirstName + " " + emp.LastName })
.Distinct()
.ToDictionary(empl => empl.ID, empl => empl.Name);
//Set combo box source to Empsource
}
Even though you are sure that no duplicate EmployeeIDs exist you may cause duplicates in the join statement if the same employee holds more than one log. Isn't that your problem?
Does the following work?
Dictionary<int, string> Empsource = tblOutOfOfficeLogs
.Select(x => x.EmployeeID).Distinct()
.Join(tblEmployees,
l => l,
emp => emp.EmployeeID,
(l, emp) => new { ID = emp.EmployeeID, Name = emp.FirstName + " " + emp.LastName })
.ToDictionary(empl => empl.ID, empl => empl.Name);
精彩评论