4

私のコードには次の行があります

var d3 = d.Union(d2).ToDictionary(s => s.Key, s => s.Value);

私はこれをたくさんする可能性が高いので、これは奇妙に感じます。ありません.ToDictionary()。辞書を結合して辞書として保持するにはどうすればよいですか?

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace ConsoleApplication1
{
    class Program
    {
        static void Main(string[] args)
        {
            var list = new List<Tuple<int, string>>();
            list.Add(new Tuple<int, string>(1, "a"));
            list.Add(new Tuple<int, string>(3, "b"));
            list.Add(new Tuple<int, string>(9, "c"));
            var d = list.ToDictionary(
                s => s.Item1, 
                s => s.Item2);
            list.RemoveAt(2);
            var d2 = list.ToDictionary(
                s => s.Item1,
                s => s.Item2);
            d2[5] = "z";
            var d3 = d.Union(d2).ToDictionary(s => s.Key, s => s.Value);
        }
    }
}
4

1 に答える 1

16

「ストレート」を使用する際の問題はUnion、辞書を辞書として解釈しないことです。辞書を として解釈しIEnumerable<KeyValyePair<K,V>>ます。ToDictionaryそのため、最後のステップが必要です。

辞書に重複したキーがない場合、これは少し速く動作するはずです:

var d3 = d.Concat(d2).ToDictionary(s => s.Key, s => s.Value);

Union2 つのディクショナリに異なる値を持つ同じキーが含まれている場合、メソッドも壊れることに注意してください。Concat同じ値に対応していても、辞書に同じキーが含まれていると壊れます。

于 2013-02-08T14:22:43.693 に答える