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

しかし、2 番目の辞書に到達すると、次のようになります。

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

2 番目の辞書に対する 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 に答える