Dictionary error: Item with this key already has been added

Dictionary error: Item with this key already has been added

我在 foreach 循环中向 Dictionary 添加项目,我发现一旦抛出此错误 - 确实有代码尝试使用相同的键添加第二次项目,我不知道这在 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);
    }
}

如果键已经存在于字典中,您可以避免异常检查:

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)

您不必使用 Add()

id[x.ParentLinkId] = rs.ID;