【问题标题】:Dictionaries: An item with the same key has already been added字典:已添加具有相同键的项目
【发布时间】:2013-02-16 05:17:48
【问题描述】:

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

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

非常感谢!

【问题讨论】:

    标签: c# asp.net-mvc dictionary


    【解决方案1】:

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

    改为这样做:

    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 可能会再次破坏秩序?
    【解决方案2】:

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

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

    【讨论】:

    • 试一试,我会告诉你结果。
    • 哇!就那么简单。非常感谢:)
    猜你喜欢
    • 2013-01-14
    • 1970-01-01
    • 2013-03-18
    • 2023-01-11
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多