【问题标题】:Comparing two sorted dictionaries比较两个排序的字典
【发布时间】:2015-07-24 15:56:05
【问题描述】:

我有两本这样的字典:

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

我需要对这两个字典进行排序,并且在输出我想要第三个字典,其中包含所有已排序的水果

【问题讨论】:

  • 第三个字典的键和值应该是什么?它们显然不能与您拥有的两个字典中的相同,因为它们之间有重复的键。
  • 第三本词典应该是什么样子的?例如,我们如何处理重复键(例如 main[0]other[0])?
  • @Chris haha​​ 我想你打败了我 :)
  • Dictionary 不是指定或关心其值排序的集合类型,因此对 Dictionary 进行排序没有任何意义(但您可以将 values 排序为另一个集合或枚举)。
  • 或者你可以使用SortedDictionary,如果水果是键,呵呵

标签: c# dictionary compare


【解决方案1】:

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

你可以像这样制作这样的字典:

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

【讨论】:

  • 谢谢,昨天我需要结束我的工作,为什么我没有完成我的问题
猜你喜欢
  • 2016-10-22
  • 1970-01-01
  • 1970-01-01
  • 2017-08-21
  • 2012-05-10
  • 1970-01-01
  • 2014-03-03
  • 2011-10-08
  • 1970-01-01
相关资源
最近更新 更多