Tuesday, 27 January 2009

Sorting Generic Collections - Redux

Using LINQ it turns out to be quite easy to sort a generic Dictionary by either Key or Value.

In these examples a list of sorted keys is returned in the 'keys' variable.

Alternately the LINQ statement can used directly in a foreach loop.

Dictionary<string, string> dict = new Dictionary<string, string>();
...


// Sort by Key
var keys = from key in dict.Keys orderby key ascending select key;


// Sort by Value
var keys = from key in dict.Keys orderby dict[key] ascending select key;


// Sort within foreach(...) by Key
foreach(string aKey in (from key in dict.Keys orderby key ascending select key)){
...
}

No comments: