字典:已经添加了相同键的项目

3

在我的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.

我最初以为我需要实例化一个新的字典(这就是“new”存在的原因),但不是这样。我做错了什么?
非常感谢!
2个回答

12
你正在对行进行去重,而不是对日期进行去重。
请改为以下方式:
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.

ToDictionary 可能会再次破坏顺序吗? - cuongle

8
您将Distinct应用于订单,而不是日期。尝试:
m_OrderManager.ListOrders()
                        .OrderBy(x => x.m_ShippedDate)
                        .Select(x =>x.m_ShippedDate)
                        .Distinct()
                        .ToDictionary(x => x.ToString(), x => x);

试一下,我会把结果告诉你。 - hsim
哇!就这么简单。非常感谢 :) - hsim

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接