C# 字典:已添加具有相同键的项

C# 字典:已添加具有相同键的项,c#,asp.net-mvc,dictionary,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()

在我的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);
}
我首先认为我添加了一个新的字典(这就是“新”出现的原因),但是没有。我做错了什么


非常感谢

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

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

你在区分行,而不是日期

改为这样做:

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)是:


试一试,我会让你恢复成绩的。哇!就这么简单。非常感谢:)
ToDictionary
可能会再次破坏订单?
m_OrderManager.ListOrders()
                        .OrderBy(x => x.m_ShippedDate)
                        .Select(x =>x.m_ShippedDate)
                        .Distinct()
                        .ToDictionary(x => x.ToString(), x => x);
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.