Home Ask Login Register

Developers Planet

Your answer is one click away!

uioporqwerty February 2016

Order Dictionary from Keys from another Dictionary

I have two dictionaries:

Dictionary<string, Tuple<T, T>> dict1
Dictionary<Enum, Tuple<string, DateTime, DateTime>> dict2

The string value in the first item in the tuple is sometimes equal to the key in the first dictionary. I would like to sort the second dictionary by the enum value and then sort the first dictionary based on the order that dict2 has. How would I be able to do that while retaining the other keys that might be in dict1? I'm able to get as far as sorting the dictionary.

var positions = new Dictionary<Enum, string>();
//This foreach loop can be simplified by a linq expression.
                    foreach (var position in dict2)
                        var isFound = dict1.Any(x => x.Key == position.Value.Item1.Value);

                        if (isFound)
                            clubPositions.Add(position.Key, position.Value.Item1.Value);

                    var sortedPositions = positions.OrderByDescending(x => x.Key);


Alex Lebedev February 2016

You can not sort dictionary as it uses hash algorithm for constant search.

Peroxy February 2016

A regular dictionary cannot be sorted. You could use a SortedDictionary, it exists for this exact purpose.

David Pine February 2016

You are looking for the SortedDictionary documented on MSDN here. You will need to instantiate them as such:

var dict1 = new SortedDictionary<string, Tuple<DateTime, DateTime>>();
var dict2 = new SortedDictionary<Enum, Tuple<string, DateTime, DateTime>>();

Once you have the sorted dictionaries instances you can use LINQ to map or filter or do whatever else is desired on them. When items are added to the dictionaries they are automatically sorted based on either the ICompare<T> for the given TKey (or the default IComparer if not explicitly provided).

One downside is the fact that this sorts based on the key alone, there is no concept of sorting based on values.

Ivan Stoev February 2016

The way I understand the question is not to sort the first dictionary, but to be able to iterate its elements in order defined by the second dictionary keys. If that's correct, the following should do the trick:

var orderedKeys = new HashSet<string>(dict2.OrderBy(e => e.Key).Select(e => e.Value.Item1));
var orderedEntries = orderedKeys.Where(dict1.ContainsKey)
    .Select(key => new KeyValuePair<string, Tuple<T, T>>(key, dict1[key]))
    .Concat(dict1.Where(e => !orderedKeys.Contains(e.Key)));

Note that it will put the entries that has no corresponding key last in the order.

Post Status

Asked in February 2016
Viewed 1,319 times
Voted 11
Answered 4 times


Leave an answer

Quote of the day: live life