C# 你如何按值对字典进行排序?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/289/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How do you sort a dictionary by value?
提问by Kalid
I often have to sort a dictionary, consisting of keys & values, by value. For example, I have a hash of words and respective frequencies, that I want to order by frequency.
我经常需要按值对由键和值组成的字典进行排序。例如,我有一个单词和相应频率的散列,我想按频率排序。
There is a SortedList
which is good for a single value (say frequency), that I want to map it back to the word.
有一个SortedList
适用于单个值(比如频率),我想将它映射回单词。
SortedDictionaryorders by key, not value. Some resort to a custom class, but is there a cleaner way?
SortedDictionary按键排序,而不是按值排序。有些人求助于自定义类,但是有更干净的方法吗?
采纳答案by Leon Bambrick
Use:
用:
using System.Linq.Enumerable;
...
List<KeyValuePair<string, string>> myList = aDictionary.ToList();
myList.Sort(
delegate(KeyValuePair<string, string> pair1,
KeyValuePair<string, string> pair2)
{
return pair1.Value.CompareTo(pair2.Value);
}
);
Since you're targeting .NET 2.0 or above, you can simplify this into lambda syntax -- it's equivalent, but shorter. If you're targeting .NET 2.0 you can only use this syntax if you're using the compiler from Visual Studio 2008 (or above).
由于您的目标是 .NET 2.0 或更高版本,您可以将其简化为 lambda 语法——它是等效的,但更短。如果您的目标是 .NET 2.0,则只有在使用 Visual Studio 2008(或更高版本)的编译器时才能使用此语法。
var myList = aDictionary.ToList();
myList.Sort((pair1,pair2) => pair1.Value.CompareTo(pair2.Value));
回答by Kalid
Looking around, and using some C# 3.0 features we can do this:
环顾四周,使用一些 C# 3.0 特性,我们可以做到这一点:
foreach (KeyValuePair<string,int> item in keywordCounts.OrderBy(key=> key.Value))
{
// do something with item.Key and item.Value
}
This is the cleanest way I've seen and is similar to the Ruby way of handling hashes.
这是我见过的最干净的方式,类似于 Ruby 处理散列的方式。
回答by Michael Stum
On a high level, you have no other choice than to walk through the whole Dictionary and look at each value.
在高层次上,您别无选择,只能浏览整个字典并查看每个值。
Maybe this helps: http://bytes.com/forum/thread563638.htmlCopy/Pasting from John Timney:
也许这有帮助:http: //bytes.com/forum/thread563638.html 从约翰蒂姆尼复制/粘贴:
Dictionary<string, string> s = new Dictionary<string, string>();
s.Add("1", "a Item");
s.Add("2", "c Item");
s.Add("3", "b Item");
List<KeyValuePair<string, string>> myList = new List<KeyValuePair<string, string>>(s);
myList.Sort(
delegate(KeyValuePair<string, string> firstPair,
KeyValuePair<string, string> nextPair)
{
return firstPair.Value.CompareTo(nextPair.Value);
}
);
回答by caryden
Use LINQ:
使用 LINQ:
Dictionary<string, int> myDict = new Dictionary<string, int>();
myDict.Add("one", 1);
myDict.Add("four", 4);
myDict.Add("two", 2);
myDict.Add("three", 3);
var sortedDict = from entry in myDict orderby entry.Value ascending select entry;
This would also allow for great flexibility in that you can select the top 10, 20 10%, etc. Or if you are using your word frequency index for type-ahead
, you could also include StartsWith
clause as well.
这也提供了很大的灵活性,因为您可以选择前 10、20 10% 等。或者,如果您使用的是 的词频索引type-ahead
,您也可以包括StartsWith
子句。
回答by Roger Willcocks
You'd never be able to sort a dictionary anyway. They are not actually ordered. The guarantees for a dictionary are that the key and value collections are iterable, and values can be retrieved by index or key, but there is no guarantee of any particular order. Hence you would need to get the name value pair into a list.
无论如何,您永远无法对字典进行排序。它们实际上并没有被订购。字典的保证是键和值集合是可迭代的,值可以通过索引或键检索,但不保证任何特定的顺序。因此,您需要将名称值对放入列表中。
回答by Alex Ruiz
The easiest way to get a sorted Dictionary is to use the built in SortedDictionary
class:
获得排序字典的最简单方法是使用内置SortedDictionary
类:
//Sorts sections according to the key value stored on "sections" unsorted dictionary, which is passed as a constructor argument
System.Collections.Generic.SortedDictionary<int, string> sortedSections = null;
if (sections != null)
{
sortedSections = new SortedDictionary<int, string>(sections);
}
sortedSections
will contains the sorted version of sections
sortedSections
将包含的排序版本 sections
回答by BSalita
Sorting a SortedDictionary
list to bind into a ListView
control using VB.NET:
使用 VB.NETSortedDictionary
对要绑定到ListView
控件的列表进行排序:
Dim MyDictionary As SortedDictionary(Of String, MyDictionaryEntry)
MyDictionaryListView.ItemsSource = MyDictionary.Values.OrderByDescending(Function(entry) entry.MyValue)
Public Class MyDictionaryEntry ' Need Property for GridViewColumn DisplayMemberBinding
Public Property MyString As String
Public Property MyValue As Integer
End Class
XAML:
XAML:
<ListView Name="MyDictionaryListView">
<ListView.View>
<GridView>
<GridViewColumn DisplayMemberBinding="{Binding Path=MyString}" Header="MyStringColumnName"></GridViewColumn>
<GridViewColumn DisplayMemberBinding="{Binding Path=MyValue}" Header="MyValueColumnName"></GridViewColumn>
</GridView>
</ListView.View>
</ListView>
回答by mythz
Or for fun you could use some LINQ extension goodness:
或者为了好玩,您可以使用一些 LINQ 扩展优点:
var dictionary = new Dictionary<string, int> { { "c", 3 }, { "a", 1 }, { "b", 2 } };
dictionary.OrderBy(x => x.Value)
.ForEach(x => Console.WriteLine("{0}={1}", x.Key,x.Value));
回答by sean
var ordered = dict.OrderBy(x => x.Value);
回答by Matt Frear
You can sort a Dictionary by value and save it back to itself (so that when you foreach over it the values come out in order):
您可以按值对字典进行排序并将其保存回自身(这样当您对它进行 foreach 时,值会按顺序出现):
dict = dict.OrderBy(x => x.Value).ToDictionary(x => x.Key, x => x.Value);
Sure, it may not be correct, but it works.
当然,它可能不正确,但它有效。