Search This Blog

Tuesday, March 18, 2014

Sorting a C# Dictionary Collection

When working with Active Directory searches I often stream matches into a C# Dictionary object (e.g., using "samaccountname" as the key and ", ()" as the value).   Since it's searching a linked list the data comes in fast but unsorted.

Unfortunately the Dictionary object doesn't support a native sort() function, but it's easy to do using a LINQ function:

/// /// Sort Dictionary structure 
/// 
public static Dictionary SortDictionaryByValue(Dictionary data)
{
        List li = new List>(data);
        li.Sort((x, y) => x.Value.CompareTo(y.Value));
        return li.ToDictionary(p => p.Key, p => p.Value);
}

Thanks to mindfiresolutions for this function.