开发者

sorting a dictionary by key?

开发者 https://www.devze.com 2023-02-07 17:21 出处:网络
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 LI

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

精彩评论

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

关注公众号