Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Sorting a dictionary by keys in the order in an Arraylist

I was asked the following question in an interview. How can I sort a Dictionary by the key, in the order which is in an array list.

So for example I have a dictionary as follows

Dictionary<string, string> stringDict = new Dictionary<string, string>();

stringDict.Add("1", "One");
stringDict.Add("7", "Seven");
stringDict.Add("6", "Six");
stringDict.Add("2", "Two");
stringDict.Add("3", "Three");
stringDict.Add("5", "Five");
stringDict.Add("4", "Four");

And an array list as follows

ArrayList stringArList = new ArrayList();

stringArList.Add("1");
stringArList.Add("2");
stringArList.Add("3");
stringArList.Add("5");
stringArList.Add("6");
stringArList.Add("7");
stringArList.Add("4");

How can I sort the dictionary in the order it is in the array list?

like image 471
user3375390 Avatar asked Apr 23 '14 21:04

user3375390


People also ask

How do you sort a dictionary by sorted?

First, we use the sorted() function to order the values of the dictionary. We then loop through the sorted values, finding the keys for each value. We add these keys-value pairs in the sorted order into a new dictionary. Note: Sorting does not allow you to re-order the dictionary in-place.

How do you arrange the order of the dictionary?

It is not possible to sort a dictionary, only to get a representation of a dictionary that is sorted. Dictionaries are inherently orderless, but other types, such as lists and tuples, are not. So you need an ordered data type to represent sorted values, which will be a list—probably a list of tuples.


2 Answers

Well you can't sort a Dictionary per se, but you can extract the key-values pairs as a list and sort those:

IEnumerable<KeyValuePair<string, string>> pairs = 
    stringDict.OrderBy(kvp => stringArList.IndexOf(kvp.Key));

But there's not a way to "traverse" dictionary items in any particular order.

You could create a SortedDictionary and provide an IComparer<string>

var d = new SortedDictionary<string, string>(stringDict, 
                                        new PositionComparer(stringArList));

With the Comparer implementation as:

public class PositionComparer : IComparer<string>
{
   private ArrayList Keys {get; set;}

   public PositionComparer(ArrayList keys)
   {
       Keys = keys;
   }

   public int Compare(string s1, string s2)
   {
       return Keys.IndexOf(s1).CompareTo(Keys.IndexOf(s2));
   }
}
like image 76
D Stanley Avatar answered Oct 29 '22 17:10

D Stanley


This will produce a list of the values sorted as required.

var sortedValues = stringDict.OrderBy(pair => stringArList.IndexOf(pair.Key))
                             .Select(pair => pair.Value)
                             .ToList();
like image 44
Daniel Brückner Avatar answered Oct 29 '22 17:10

Daniel Brückner