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

时间:2011-05-03 19:07:39

标签: c# .net visual-studio linq lambda

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

 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


        }

1 个答案:

答案 0 :(得分:4)

即使您确定不存在重复的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);