1
我收到的错误:参数异常“项目以相同的密钥已经被添加”
System.ArgumentException was unhandled by user code HResult=-2147024809 Message=An item with the same key has already been added.
当试图在这个应用程序加载页面。 Visual Studio指向此行:
_db.GroupProgramPlans.Select(x => new {Code = x.GroupCode, Name = x.Group}).Distinct().ForEach(x=> groups.Add(x.Code,x.Name));
作为引起错误的行。代码查询的表没有PK。我已经在表格中寻找重复的行。表中只有大约30行,并且它们具有公共列值,但没有任何重复行。我试图删除.Distinct()。不确定是什么原因导致错误以及应如何处理。以下是代码。
public ActionResult Index()
{
var groups = new Dictionary<string,string>();
_db.GroupProgramPlans.Select(x => new {Code = x.GroupCode, Name = x.Group}).Distinct().ForEach(x=> groups.Add(x.Code,x.Name));
ViewBag.Groups = groups;
return View(_db.DocumentTemplates.Where(x => x.Active == true));
}
'Distinct'适用于您不是匿名对象到'GroupCode'。对于匿名对象:如果**所有属性**具有相同的值,则它们相等。使用* GroupBy *作为'GroupCode'。 – EZI