PositiveGuy
PositiveGuy

Reputation: 20212

LINQ OrderBy not working on Dictionary Key

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.

Upvotes: 1

Views: 4044

Answers (2)

yammit
yammit

Reputation: 41

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

Upvotes: 3

Mohayemin
Mohayemin

Reputation: 3870

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.

Upvotes: 6

Related Questions