2015-07-01 80 views
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)); 
     } 
+0

'Distinct'適用於您不是匿名對象到'GroupCode'。對於匿名對象:如果**所有屬性**具有相同的值,則它們相等。使用* GroupBy *作爲'GroupCode'。 – EZI

回答

1

我會寫這樣的事情

var groups = _db.GroupProgramPlans 
       .GroupBy(x=>x.GroupCode) 
       .Select(x=>x.FirstOrDefault()) 
       .ToDictionary(x=>x.GroupCode,x=>x.Group); 
相關問題