uioporqwerty
uioporqwerty

Reputation: 317

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

Upvotes: 0

Views: 1016

Answers (4)

Ivan Stoev
Ivan Stoev

Reputation: 205629

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.

Upvotes: 2

David Pine
David Pine

Reputation: 24535

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.

Upvotes: 4

Peroxy
Peroxy

Reputation: 646

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

Upvotes: 1

Alex Lebedev
Alex Lebedev

Reputation: 609

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

Upvotes: 1

Related Questions