字典错误:已添加具有此键的项目

时间:2015-01-03 17:42:06

标签: c# dictionary foreach

我在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);
    }
}

2 个答案:

答案 0 :(得分:4)

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

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

请记住,来自MSDN:

  

如果要从某些自定义数据类型的对象序列中返回不同的元素,则必须在类中实现IEquatable泛型接口。

此处有更多信息:

Enumerable.Distinct Method (IEnumerable)

答案 1 :(得分:0)

您不必使用Add()

id [x.ParentLinkId] = rs.ID;