capdragon
capdragon

Reputation: 14899

LINQ: An item with the same key has already been added

I'm getting the following error when loading my data record into objects using LINQ. It was working before I added two extra fields dataLevelId and dataLevel. I must done something I shouldn't have because now it's not working. Can anyone spot what it is i'm doing wrong?

{System.ArgumentException: An item with the same key has already been added.
   at System.ThrowHelper.ThrowArgumentException(ExceptionResource resource)
   at System.Collections.Generic.Dictionary`2.Insert(TKey key, TValue value, Boolean add)
   at System.Collections.Generic.Dictionary`2.Add(TKey key, TValue value)...

This is my code:

var groups = reader.Cast<IDataRecord>()
    .GroupBy(dr => new { ID = (int)dr["productId"] })
    .GroupBy(g => g.Key.ID);

products = (
    from productGroup in groups
    let productRow = productGroup.First().First()
    select new Product()
    {
        ID = Convert.ToString((int)productRow["productId"]),
        Name = !DBNull.Value.Equals(productRow["name"]) ? (string)productRow["name"] : "",
        OutputFormats =
        (
            from formatRow in productGroup.First()
            select new OutputFormat()
            {
                ID = !DBNull.Value.Equals(formatRow["outputFormatId"]) ? Convert.ToString(formatRow["outputFormatId"]) : "",
                Name = !DBNull.Value.Equals(formatRow["outputFormat"]) ? (string)formatRow["outputFormat"] : "",
                DataLevelID = !DBNull.Value.Equals(formatRow["dataLevelId"]) ? Convert.ToString(formatRow["dataLevelId"]) : "",
                DataLevel = !DBNull.Value.Equals(formatRow["dataLevel"]) ? (string)formatRow["dataLevel"] : ""
            }
        ).ToSerializableDictionary(p => p.ID)
    }
).ToSerializableDictionary(p => p.ID);

And here is the data that gets returned in my data record. enter image description here

And yes, OutputFormat and Product classes have only string properties (including Ids).

Update:

What i want is to fill my SerializableDictionary<string, Product> products. It should have 3 products and each product should have their corresponding outputformats.

public class Product
{
    public string ID { get; set; }
    public string Name { get; set; }
    public SerializableDictionary<string, OutputFormat> OutputFormats { get; set; }
}

public class OutputFormat
{
    public string ID { get; set; }
    public string Name { get; set; }
    public string DataLevelID { get; set; }
    public string DataLevel { get; set; }
}

Upvotes: 3

Views: 7512

Answers (1)

Sampath
Sampath

Reputation: 65870

You're using a dictionary and you're trying to add an item with same key.

It's like below.

Dictionary.add("key1","item1")
Dictionary.add("key2","item2")
Dictionary.add("key1","item3") << not allowed.

Check your code and avoid that.

Upvotes: 5

Related Questions