我有2个词典:
1. Dictionary<String, Person>
2. Dictionary<Person, int>
我想按值排序第一个字典(即Person(s)),它排序与第二个字典中的键(即Person(s))的顺序完全相同。什么是最简单的方法?
答案 0 :(得分:0)
尝试以下方法:
var ordered = dictionary1.OrderBy(p => dictionary2[p.Value]).ToArray();
答案 1 :(得分:0)
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);
}