2015-01-03 32 views
-1

我在向foreach循環中的詞典中添加項目,我發現一旦拋出這個錯誤 - 確實有代碼嘗試添加第二個項目與同一個鍵,我不有任何想法這可能發生在foreach循環內。下面是代碼:
字典錯誤:帶此項的項目已被添加

private void ImportData() 
{ 
    try 
    { 
     var a = (from b in _db.LinkData 
       join c in _db.Links on b.ParentLinkId equals c.Id 
       where c.IsParsed == null & c.LinkAddress.Contains("olx.ae") 
       select b).Take(500).Distinct().ToList(); 
     Dictionary<int?, long?> id = new Dictionary<int?, long?>(); 
     if (a.Any()) 
     { 
      foreach (var x in a) 
      { 
       HHserviceClient hh = new HHserviceClient(); 
       var rs = new HHResponse(); 
       var rq = new HHPostPropertyRequest 
       { 
        Amenities = x.Amenities, 
        Area = x.Area, 
        BathRooms = x.BathRooms, 
        Bedrooms = x.Bedrooms, 
        City = x.City, 
        Company = x.Company, 
        Contact = x.Contact, 
        Country = x.Country, 
        CustomerID = 1000, 
        Description = x.Description, 
        Email = x.Email, 
        LandLineNo = x.LandLineNo, 
        Lattitude = x.Lattitude, 
        Location = x.Location, 
        Longitude = x.Longitude, 
        MobileNo = x.MobileNo, 
        Prptype = x.Prptype, 
        PrpSource = x.PrpSource, 
        Price = x.Price, 
        Parkings = x.Parkings, 
        Title = x.Title 
       }; 
       rs = hh.PostProperty(rq); 
       if (rs.ID.HasValue) 
       { 
        //Error thrown here 
        id.Add(x.ParentLinkId, rs.ID); 
       } 
       else 
       { 
        continue; 
       } 
      } 
     } 
     UpdateLink(id); 
    } 
    catch (Exception ex) 
    { 
     throw new Exception(ex.Message); 
    } 
} 
+0

你可以嘗試改變你的問題嗎?另外,**錯誤是什麼**? –

回答

4

就可避免異常檢查,如果關鍵是已經存在於詞典:

if (!id.ContainsKey(x.ParentLinkId) 
    id.Add(x.ParentLinkId, rs.ID); 

記住這一點,從MSDN:

If you want to return distinct elements from sequences of objects of some custom data type, you have to implement the IEquatable generic interface in the class.

更多信息在這裏:

Enumerable.Distinct Method (IEnumerable)

+0

謝謝,我真的很驚訝這個異常,因爲通常foreach可能不會處理兩次相同的值。 –

+3

@ andrey.shedko它沒有。可能是由你的LINQ查詢產生的列表有一些具有相同'ParentLinkId'的對象。 – dario

相關問題