【问题标题】:sorting a dictionary by key?按键排序字典?
【发布时间】:2011-06-17 22:58:29
【问题描述】:

我需要按字典的键对字典进行排序,因为 WP7 不支持SortedDictionary。我怎样才能做得好、容易和优化?

【问题讨论】:

标签: c# windows-phone-7 sorting dictionary


【解决方案1】:

此堆栈溢出问题包括使用 LINQ 的解决方案。

How do you sort a dictionary by value?

【讨论】:

  • 我试过这个代码: Dictionary dict = new Dictionary(); dict.Add("3", "三"); dict.Add("1", "one"); dict.Add("2", "two"); var sortedDict = (from entry in dict orderby entry.Key升序选择条目);这有效,但 sortedDict 不是字典。我怎样才能使它成为一本字典?另外,我尝试了 dict.OrderBy(x => x.Key);这不起作用。为什么?
  • 解决了:dict = (from entry in dict orderby entry.Key升序选择条目).ToDictionary(x=>x.Key, x=>x.Value);
【解决方案2】:

我试过这个代码:

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);
}

这可行,但 sortedDict 不是字典。我解决了:

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

【讨论】:

  • 解决了:dict = (from entry in dict orderby entry.Key 升序选择条目).ToDictionary(x=>x.Key, x=>x.Value);
猜你喜欢
  • 2021-11-27
  • 2015-10-10
  • 2012-07-30
  • 1970-01-01
  • 2017-08-20
  • 2016-11-22
  • 2017-05-30
  • 2020-06-09
相关资源
最近更新 更多