开发者

sorting a dictionary by key?

I need to sort a dictionary by it's key, since WP开发者_开发知识库7 does not support SortedDictionary. How can I do it nice, easy and optimal?


This stack overflow question includes a solution using LINQ.

How do you sort a dictionary by value?


i tried this code:

Dictionary<string, string> dict = new Dictionary<string,string>();
dict.Add("3", "three");
dict.Add("1", "one");
dict.Add("2", "two");

var sortedDict = (from entry in dict orderby entry.Key ascending select entry); 

foreach (var k in sortedDict)
{
    Console.WriteLine("key:{0}, val={1} ", k.Key, k.Value);
}

This works, but sortedDict is not a dictionary. I solved it:

sortedDict = (from entry in dict orderby entry.Key ascending select entry)
            .ToDictionary(x => x.Key, x => x.Value); 
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜