Sort Dictionary by values using keys of another dictionary
I have 2 dictionaries:
1. Dictionary<String, Person>
2. Dictionary<Person, in开发者_C百科t>
I would like to sort the first dictionary by values (i.e. Person(s)) ordering it exactly the same as the order of the keys (i.e. Person(s)) in the 2nd Dictionary. What would be the simplest way?
Try the following:
var ordered = dictionary1.OrderBy(p => dictionary2[p.Value]).ToArray();
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);
}
精彩评论