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

本文关键字:添加 字典 | 更新日期: 2023-09-27 18:01:41

在我的MVC应用程序中,我使用2字典来填充下拉列表的SelectList。这些字典将提供日期作为字符串和datetime值。

我有这段代码,用于第一个正常工作的字典:

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"存在的原因),但不是。我做错了什么?

非常感谢!

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

您是在区分行,而不是日期。

这样做:

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

不要排序了。字典无序


我的标准模式是:

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

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

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