词典:已添加具有相同键的项目

时间:2013-03-01 16:25:41

标签: c# asp.net-mvc dictionary

在我的MVC应用程序中,我使用2个词典来填充DropDownList的SelectList。这些词典将提供日期作为字符串和日期时间值。

我有第一个字典的代码块可以正常工作:

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

但是当我到达第二本词典时:

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

我在第二个字典的LINQ请求上遇到运行时错误:

An item with the same key has already been added.

我首先虽然我添加实例化一个新字典(这是“新”存在的原因),但不是。我做错了什么?

非常感谢!

2 个答案:

答案 0 :(得分:9)

你是对行的区别,而不是日期。

请改为:

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

不要打扰排序。字典是无序的。


我的标准模式(因为我不屑于Distinct)是:

dictionary = source
  .GroupBy(row => row.KeyProperty)
  .ToDictionary(g => g.Key, g => g.First()); //choose an element of the group as the value.

答案 1 :(得分:8)

您将Distinct应用于订单,而不是日期。尝试

m_OrderManager.ListOrders()
                        .OrderBy(x => x.m_ShippedDate)
                        .Select(x =>x.m_ShippedDate)
                        .Distinct()
                        .ToDictionary(x => x.ToString(), x => x);