c# - LINQ:已添加具有相同键的项目

标签 c# linq

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

这是我的数据记录中返回的数据。 enter image description here

是的,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; }
}

最佳答案

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

如下图

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

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

关于c# - LINQ:已添加具有相同键的项目,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14322173/

相关文章:

c# - 使用数组或泛型时 TestCase 在 NUnit 中的显示名称

使用Parameters.AddWithValue 返回参数表示的C# 和MySQL 错误

c# - 无法使用 LINQ to XML 读取 XML 注释

c# - 检查一组对象中的任何一个属性是否与一组字符串中的任何一个相匹配的 lambda 表达式是什么?

c# - 根据日期时间过滤大列表

c# - WebClient 上传文件不起作用

c# - SQL Server 选择低效计划(通过 EntityFramework)

c# - 使用 C++/CLI 的任务并行库 Task.ContinueWith

c# - LINQ & IEnumerable<String> 重新求值

c# - 将数据表转换为 IList c#