词典:已添加具有相同键的项目

hsi*_*sim 2 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()
                        .OrderBy(x => x.m_OrderDate)
                        .Distinct()
                        .ToDictionary(x => x.m_OrderDate.ToString(), x => x.m_OrderDate);
}
Run Code Online (Sandbox Code Playgroud)

但是当我到达第二本词典时:

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);
}
Run Code Online (Sandbox Code Playgroud)

我在第二个字典的LINQ请求上遇到运行时错误:

An item with the same key has already been added.
Run Code Online (Sandbox Code Playgroud)

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

非常感谢!

Amy*_*y B 9

你是不同的行,而不是日期.

改为:

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);
}
Run Code Online (Sandbox Code Playgroud)

不要打扰排序.字典是无序的.


我的标准模式(因为我不屑于Distinct)是:

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


Ste*_*eri 8

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

m_OrderManager.ListOrders()
                        .OrderBy(x => x.m_ShippedDate)
                        .Select(x =>x.m_ShippedDate)
                        .Distinct()
                        .ToDictionary(x => x.ToString(), x => x);
Run Code Online (Sandbox Code Playgroud)