-4

I have a Dictionary<int?,List<string>>. I need to output pairs of keys and values sorted by keys in ascending order. First, I think to use OrderedDictionary but it saves both keys and values in type of object. Maybe somehow it could be done through the extension methods?

Max King
  • 15
  • 6
  • Please read this: https://stackoverflow.com/questions/4007782/the-order-of-elements-in-dictionary/4007787#4007787 – Sebastian Hofmann May 20 '18 at 15:34
  • 1
    [SortedDictionary Class](https://msdn.microsoft.com/en-us/library/f7fta44c%28v=vs.110%29.aspx?f=255&MSPPError=-2147217396) – Slai May 20 '18 at 15:37
  • I was about to say that you can collect all keys in a List and sort them and then access it accordingly in ordered manner. Open to any kind of ideas regarding what is wrong/right with this solution. – user9816091 May 20 '18 at 15:37
  • Actually, do you only want a `List` only the sorted keys? – Attersson May 20 '18 at 15:39
  • Yes, but I'll output both keys and values – Max King May 20 '18 at 15:44
  • 4
    People are trying to answer your question but they are getting downvoted because your question is not clear. Please provide an example of what you have and what you expect the output to be. Also, where is your code? Without code your question can be interpreted many ways. – CodingYoshi May 20 '18 at 16:02
  • @CodingYoshi I'd think the latest edit makes it much clearer. I've removed my close vote – Camilo Terevinto May 20 '18 at 16:19

2 Answers2

2

You have two options here:

  1. Use a SortedList<TKey,TValue>/SortedDictionary<TKey,TValue>:

    var sortedData = new SortedList<int?, List<string>>(currentDictionary);
    
  2. Use Linq's OrderBy:

    var sortedData = currentDictionary.OrderBy(x => x.Key);
    

You can use any of these options with the following printing:

foreach (var entry in sortedData)
{
    Console.WriteLine("Key: {0}, Values: ", entry.Key);

    foreach (var value in entry.Value)
    {
        Console.WriteLine(value);
    }
}
Camilo Terevinto
  • 31,141
  • 6
  • 88
  • 120
1
Dictionary<int?, List<string>> yourDictionary = GetTheDictionary();
var sortedKeys = yourDictionary.Select(kvp => kvp.Key).OrderBy(k => k);

This will give you a list of all of your keys in ascending order

If you want your dictionary the same. Ie still as Key Value Pairs. Just ordered by the key then you need to do.

yourDictionary.OrderBy(kvp => kvp.Key);
Dave
  • 2,829
  • 3
  • 17
  • 44