使用 LINQ 将我的数据记录加载到对象中时出现以下错误。在我添加两个额外的字段之前它一直在工作 dataLevelId
和 dataLevel
.我必须做一些我不应该做的事情,因为现在它不起作用了。谁能看出我做错了什么?
{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; }
}
最佳答案
您正在使用字典并尝试添加具有相同键的项目。
如下图
Dictionary.add("key1","item1")
Dictionary.add("key2","item2")
Dictionary.add("key1","item3") << not allowed.
检查你的代码并避免这种情况。
关于c# - LINQ:已添加具有相同键的项目,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14322173/