Lambda/Linq错误“已经添加了具有相同键的项”

本文关键字:错误 Linq 添加 Lambda | 更新日期: 2023-09-27 17:54:23

"已添加具有相同键的项"是我得到的错误。我做错了什么?提前感谢您的帮助。

 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

        }

Lambda/Linq错误“已经添加了具有相同键的项”

即使您确定不存在重复的employeeid,如果同一雇员持有多个日志,也可能在join语句中导致重复。这不是你的问题吗?

下面的工作吗?

        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);