比较两个排序好的字典



我有两个这样的字典:

            Dictionary<int, string> main = new Dictionary<int, string>();
        Dictionary<int, string> other = new Dictionary<int, string>();
        main.Add(0, "fruit;banana");
        main.Add(1, "fruit;apple");
        main.Add(2, "fruit;cherry");
        main.Add(3, "fruit;pear");
        other.Add(0, "fruit;blueberry");
        other.Add(1, "fruit;pear");
        other.Add(2, "fruit;orange");

我需要对这两个字典进行排序,在输出处我需要第三个字典,它包含所有已排序的水果

虽然您不清楚您想要第三个字典是什么样子的问题,但我猜您想要的是一个字典,其中值是前两个字典中所有排序的结果,而键只是简单地计数(就像前两个字典一样)。

你可以这样做一个字典:

Dictionary<int, string> allFruits =
    main.Values.Concat(other.Values)
    .OrderBy(f => f)
    .Select((f, i) => new { fruit = f, index = i })
    .ToDictionary(o => o.index, o => o.fruit);

基于给定的mainother字典的结果:

[0, "fruit;apple"]
[1, "fruit;banana"]
[2, "fruit;blueberry"]
[3, "fruit;cherry"]
[4, "fruit;orange"]
[5, "fruit;pear"]
[6, "fruit;pear"]

如果你不想让fruit;pear出现两次,你可以在那里插入一个.Distinct()调用:

Dictionary<int, string> allFruits =
    main.Values.Concat(other.Values)
    .Distinct()
    .OrderBy(f => f)
    .Select((f, i) => new { fruit = f, index = i })
    .ToDictionary(o => o.index, o => o.fruit);

最新更新