参数异常“已添加具有相同键的项目”
Argument Exception “Item with Same Key has already been added”
我收到错误消息:
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));
作为导致错误的行。 table 代码正在查询没有 PK。我有 运行 通过 table 寻找重复的行。 table 中只有大约 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));
}
我会这样写
var groups = _db.GroupProgramPlans
.GroupBy(x=>x.GroupCode)
.Select(x=>x.FirstOrDefault())
.ToDictionary(x=>x.GroupCode,x=>x.Group);
我收到错误消息:
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));
作为导致错误的行。 table 代码正在查询没有 PK。我有 运行 通过 table 寻找重复的行。 table 中只有大约 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));
}
我会这样写
var groups = _db.GroupProgramPlans
.GroupBy(x=>x.GroupCode)
.Select(x=>x.FirstOrDefault())
.ToDictionary(x=>x.GroupCode,x=>x.Group);