我经常需要根据值对字典(由键和值组成)进行排序。例如,我有一个单词和相应频率的散列,我想按频率排序。

有一个SortedList,它适用于单个值(比如频率),我想把它映射回单词。

SortedDictionary按键排序,而不是按值。有些人求助于自定义课程,但有没有更干净的方法呢?


当前回答

下面的代码片段按值对Dictionary进行排序。

代码首先创建一个字典,然后使用OrderBy方法对条目进行排序。

public void SortDictionary()  
{  
  
    // Create a dictionary with string key and Int16 value pair  
    Dictionary<string, Int16> AuthorList = new Dictionary<string, Int16>();  
    AuthorList.Add("Mahesh Chand", 35);  
    AuthorList.Add("Mike Gold", 25);  
    AuthorList.Add("Praveen Kumar", 29);  
    AuthorList.Add("Raj Beniwal", 21);  
    AuthorList.Add("Dinesh Beniwal", 84);   
  
    // Sorted by Value  
  
    Console.WriteLine("Sorted by Value");  
    Console.WriteLine("=============");  
    foreach (KeyValuePair<string, Int16> author in AuthorList.OrderBy(key => key.Value))  
    {  
        Console.WriteLine("Key: {0}, Value: {1}", author.Key, author.Value);  
    }  
} 

其他回答

或者为了好玩,你可以使用一些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));

反正你也不可能对字典进行排序。它们实际上并不是有序的。字典的保证是键和值集合是可迭代的,值可以通过索引或键检索,但不保证任何特定的顺序。因此,您需要将名称值对放入一个列表中。

使用VB对SortedDictionary列表进行排序以绑定到ListView控件。NET:

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:

<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>

所需的命名空间:使用System.Linq;

Dictionary<string, int> counts = new Dictionary<string, int>();
counts.Add("one", 1);
counts.Add("four", 4);
counts.Add("two", 2);
counts.Add("three", 3);

按描述排序:

foreach (KeyValuePair<string, int> kvp in counts.OrderByDescending(key => key.Value))
{
// some processing logic for each item if you want.
}

按Asc排序:

foreach (KeyValuePair<string, int> kvp in counts.OrderBy(key => key.Value))
{
// some processing logic for each item if you want.
}

假设你有一个字典,你可以直接使用下面一行对它们进行排序:

var x = (from c in dict orderby c.Value.Order ascending select c).ToDictionary(c => c.Key, c=>c.Value);