2

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

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

非常感谢!

4

2 回答 2

10

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

改为这样做:

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.
于 2013-03-01T16:30:56.523 回答
8

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

m_OrderManager.ListOrders()
                        .OrderBy(x => x.m_ShippedDate)
                        .Select(x =>x.m_ShippedDate)
                        .Distinct()
                        .ToDictionary(x => x.ToString(), x => x);
于 2013-03-01T16:28:22.107 回答