3

使用 LINQ 将数据记录加载到对象中时出现以下错误。在我添加两个额外字段dataLevelIddataLevel. 我必须做一些我不应该做的事情,因为现在它不起作用了。谁能发现我做错了什么?

{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)...

这是我的代码:

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);

这是在我的数据记录中返回的数据。 在此处输入图像描述

是的,OutputFormat 和 Product 类只有字符串属性(包括 Id)。

更新:

我想要的是填补我的SerializableDictionary<string, Product> products. 它应该有 3 个产品,每个产品都应该有相应的输出格式。

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; }
}
4

1 回答 1

5

您正在使用字典,并且尝试添加具有相同键的项目。

就像下面这样。

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

检查您的代码并避免这种情况。

于 2013-01-14T16:20:55.257 回答