Go to home page mail me! RSS Feed
FoxMetrics Web Analytics

Dictionary Sorting – by value or key

Wednesday, September 15, 2010 10:23 AM

if you have been developing more than a few weeks it will be made apparent that you can’t sort a dictionary because of obvious reasons which I won’t go into,all you need to is that its by design and not a bug. therefore, here are some simple ways you can possible sort a dictionary.

lets populate a dictionary with some data.

// Populate some data into a dictionary
Dictionary<string, int> d = new Dictionary<string, int>();
for (int i = 0; i < 100; i++)
{
    d.Add("Rydal" + i.ToString(), i);
}

List Sort

List<KeyValuePair<string, int>> l = new List<KeyValuePair<string, int>>(d);
l.Sort(delegate(KeyValuePair<string, int> first, KeyValuePair<string, int> next)
{
    //return first.Value.CompareTo(next.Value); // ascending
    return next.Value.CompareTo(first.Value); // descending
});
d.Clear();
foreach (KeyValuePair<string, int> item in l)
{
    d.Add(item.Key, item.Value);
}

LINQ Sort

var sortedvalues = from k in d
                   orderby k.Value descending
                   select k;
 
var sortedkeys = from k in d.Keys
                 orderby d[k] descending
                 select k;

 

LAMBDA

l.Sort((first, next) => { return first.Value.CompareTo(next.Value); });

 

there you go, home it helps, one of the is bound to work in your environment.

DotNetKicks Image

Your Comments.

No comments posted yet.

Your Reply.

Comment Form.

Fields denoted with a "*" are required.

You may also like to leave your email or website.

 
Please add 3 and 1 and type the answer here:

Preview Your Comment.

 
Next entries »