C# 字典:已添加具有相同键的项目
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/15162247/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Dictionaries: An item with the same key has already been added
提问by hsim
In my MVC app I am using 2 dictionaries to populate SelectList for DropDownList. Those dictionaries will be supplied with dates as string and datetime values.
在我的 MVC 应用程序中,我使用 2 个字典为 DropDownList 填充 SelectList。这些字典将提供日期作为字符串和日期时间值。
I have this chunk of code for the first dictionary that works just fine:
我有第一个字典的这段代码,它工作得很好:
if (m_DictDateOrder.Count == 0)
{
m_DictDateOrder = new Dictionary<string, DateTime>();
m_DictDateOrder =
m_OrderManager.ListOrders()
.OrderBy(x => x.m_OrderDate)
.Distinct()
.ToDictionary(x => x.m_OrderDate.ToString(), x => x.m_OrderDate);
}
But when I get to the second dictionary:
但是当我读到第二本字典时:
if (m_DictDateShipped.Count == 0)
{
m_DictDateShipped = new Dictionary<string, DateTime>();
m_DictDateShipped =
m_OrderManager.ListOrders()
.OrderBy(x => x.m_ShippedDate)
.Distinct()
.ToDictionary(x => x.m_ShippedDate.ToString(), x => x.m_ShippedDate);
}
I get a runtime error on the LINQ request for the second dictionary:
我对第二个字典的 LINQ 请求出现运行时错误:
An item with the same key has already been added.
I first though that I add to instantiate a new dictionary (that's the reason for the "new" presence), but nope. What did I do wrong?
我首先虽然我添加来实例化一个新字典(这就是“新”存在的原因),但不是。我做错了什么?
Thanks a lot!
非常感谢!
采纳答案by Stefano Altieri
You applied the Distinct to the order, not to the date. Try
您将 Distinct 应用于订单,而不是日期。尝试
m_OrderManager.ListOrders()
.OrderBy(x => x.m_ShippedDate)
.Select(x =>x.m_ShippedDate)
.Distinct()
.ToDictionary(x => x.ToString(), x => x);
回答by Amy B
You are Distinct'ing the rows, not the dates.
您正在区分行,而不是日期。
Do this instead:
改为这样做:
if (m_DictDateShipped.Count == 0)
{
m_DictDateShipped = m_OrderManager.ListOrders()
//make the subject of the query into the thing we want Distinct'd.
.Select(x => x.m_ShippedDate)
.Distinct()
.ToDictionary(d => d.ToString(), d => d);
}
Don't bother sorting. Dictionary is unordered.
不要打扰排序。字典是无序的。
My standard pattern for this (since I have disdain for Distinct) is:
我对此的标准模式(因为我不屑于 Distinct)是:
dictionary = source
.GroupBy(row => row.KeyProperty)
.ToDictionary(g => g.Key, g => g.First()); //choose an element of the group as the value.