【问题标题】:Sort Dictionary by values using keys of another dictionary使用另一个字典的键按值对字典进行排序
【发布时间】:2011-06-19 06:39:20
【问题描述】:

我有两本词典:

1. Dictionary<String, Person>
2. Dictionary<Person, int>

我想按值(即 Person(s))对第一个字典进行排序,使其与第二个字典中键的顺序(即 Person(s))完全相同。最简单的方法是什么?

【问题讨论】:

  • Dictionary 没有排序,那么第二个Dictionary 中的键顺序是什么意思?你的意思是你有一个IComparer&lt;Person&gt;?无论如何,您所说的对字典进行排序是什么意思?
  • 多吃鸡肉。接受更多答案。
  • @Shahid - 你确定你指的是字典的键而不是第二个字典的值(int)吗?
  • 好的,很抱歉没有正确解释。我可以看到有一个 OrderBy(keySelector)。我想使用类似的东西在第一个字典上做一个 OrderBy 'Values' 并使用第二个字典中的'Keys'列表的顺序。
  • 顺便说一下,在这种情况下,第二个字典中的键是完全相同的(大小和值),只是顺序不同

标签: c# .net sorting dictionary


【解决方案1】:
Dictionary<string, int> first = new Dictionary<string, int>();
Dictionary<int, string> second = new Dictionary<int, string>();
first.Add("a", 1);
first.Add("c", 3);
first.Add("b", 2);
first.Add("g", 7);
first.Add("d", 4);

second.Add(3, "c");
second.Add(1, "a");
second.Add(7, "g");
second.Add(2, "b");
second.Add(4, "d");

Dictionary<string, int> final = new Dictionary<string, int>();
second.ToList().ForEach(s =>
{
    if (first.ContainsValue(s.Key))
        final.Add(s.Value, s.Key);
});

foreach (var item in final)
{
    Console.WriteLine(item.Key + " " + item.Value);
}

【讨论】:

    【解决方案2】:

    尝试以下方法:

    var ordered = dictionary1.OrderBy(p => dictionary2[p.Value]).ToArray();
    

    【讨论】:

    • 这是按第二个字典的值排序,而不是键。坦率地说,问题中没有足够的信息。
    • 抱歉,误读了问题。你说的对。对我来说,他想按值排序似乎很明显,因为正如你所说,第二个字典中没有Person 的顺序。感谢您注意到这一点。
    猜你喜欢
    • 1970-01-01
    • 2012-03-19
    • 1970-01-01
    • 1970-01-01
    • 2011-07-08
    • 1970-01-01
    • 1970-01-01
    • 2019-01-25
    • 2010-11-18
    相关资源
    最近更新 更多