1

seems ok to me but my list still isn't ordered by my key.

    var tagNamesAndRoutes = new Dictionary<string, string>();

    foreach (string name in tagNames)
    {
        tagNamesAndRoutes.Add(name, routeConstant);
    }

Example of dictionary values:

Key       Value
"NUnit"     "/Category"
"WCF"       "/Category"
"ReSharper" "/Category"

and so on.

I tried to sort it via typical LINQ:

tagNamesAndRoutes.OrderBy(c => c.Key);

but it's not sorted after the fact.

PositiveGuy
  • 17,621
  • 26
  • 79
  • 138
  • Did you try SortedDictionary? – Tzu May 17 '15 at 04:23
  • Were you using the return value? OrderBy has no side effect. e.g. var sortedTagNamesAndRoutes = tagNamesAndRoutes.OrderBy(c => c.Key); – user2588666 May 17 '15 at 04:26
  • Tested your code and it seems to work fine. You need to use what `OrderBy` returns. It doesn`t make changes to the original dictionary. – Thiago Sá May 17 '15 at 04:28
  • possible duplicate of [LINQ - dynamic orderby clause does not work](http://stackoverflow.com/questions/9409878/linq-dynamic-orderby-clause-does-not-work) – Jason Watkins May 17 '15 at 04:34

2 Answers2

6

OrderBy actually returns you the ordered collection. Try this:

var orderedTagNamesAndRoutes = tagNamesAndRoutes.OrderBy(c => c.Key);

Then use orderedTagNamesAndRoutes.

If you want your dictionary to be sorted itself, you can use SortedDictionary. Try:

var tagNamesAndRoutes = new SortedDictionary<string, string>();

You do not need to call OrderBy in this case. The dictionary is always sorted by the key.

Mohayemin
  • 3,841
  • 4
  • 25
  • 54
  • the first changes it to an Enumerable so I'd have to cast it back to a dictionary...I'd rather prevent a cast, so probably second is better unless anyone knows of any performance issues with SortedDictionary..but preventing casting is far more performant. – PositiveGuy May 17 '15 at 05:44
  • 1
    @WeDoTDD - You wouldn't be doing a "cast" to get it back. You'd need to build a new dictionary from the ordered enumerable. – Enigmativity May 17 '15 at 06:31
3

OrderBy returns an IOrderedEnumerable which you can iterate in the sorted order and doesn't modify the actual dictionary.

So you need to do something like

var sorted = tagNamesAndRoutes.OrderBy(c => c.Key);
foreach (string name in sorted) {
    ...
}

The Dictionary type itself has no notion of order for its keys. You can use SortedDictionary if you always want the keys sorted.

https://msdn.microsoft.com/en-us/library/vstudio/bb534966%28v=vs.100%29.aspx

Nomesh DeSilva
  • 1,649
  • 4
  • 25
  • 43
yammit
  • 41
  • 5