我经常需要对一个字典(包含键和值)按值进行排序。例如,我有一个单词和相应频率的哈希表,我想按频率排序。
有一个SortedList
适用于单个值(比如频率),我想将其映射回单词。
SortedDictionary按键而不是值进行排序。一些人会使用自定义类,但是否有更简洁的方法呢?
我经常需要对一个字典(包含键和值)按值进行排序。例如,我有一个单词和相应频率的哈希表,我想按频率排序。
有一个SortedList
适用于单个值(比如频率),我想将其映射回单词。
SortedDictionary按键而不是值进行排序。一些人会使用自定义类,但是否有更简洁的方法呢?
使用 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;
这也将允许更大的灵活性,因为您可以选择前10、20、10%等内容。或者,如果您正在使用单词频率索引进行type-ahead
,您还可以包括StartsWith
子句。
IEnumerable<KeyValuePair<TKey, TValue>>
或OrderedDictionary<TKey, TValue>
,或者一开始就使用SortedDictionary
。对于普通的Dictionary
,MSDN明确说明:“返回项的顺序是未定义的”。看起来@rythos42的最新编辑有责任。 :) - Boris B.Stopwatch()
)进行比较,并发现使用LINQ的时间增加了近350%。使用其他方法排序的四个成员列表= 0.0039511秒;使用LINQ方法排序的相同四个成员列表= 0.0130195秒。 - brandeded使用:
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);
}
);
由于您的目标是.NET 2.0或更高版本,因此可以将其简化为lambda语法--它是等效的,但更短。如果您的目标是.NET 2.0,则只有在使用来自Visual Studio 2008(或更高版本)的编译器时才能使用此语法。
var myList = aDictionary.ToList();
myList.Sort((pair1,pair2) => pair1.Value.CompareTo(pair2.Value));
myList.Sort((x,y)=>x.Value.CompareTo(y.Value));
。 - Arnis LapsaIEnumerable
接口,所以你可以像这样获取一个排序后的列表:var mySortedList = myDictionary.OrderBy(d => d.Value).ToList();
- BrainSlugs83你可以使用以下代码:
var ordered = dict.OrderBy(x => x.Value).ToDictionary(x => x.Key, x => x.Value);
您可以按值对字典进行排序,并将其保存回原字典(以便在使用 foreach 循环时,值按顺序输出):
dict = dict.OrderBy(x => x.Value).ToDictionary(x => x.Key, x => x.Value);
当然,这可能不正确,但它是可行的。海伦定律意味着这很有可能会继续起作用。
.ToDictionary(...)
。这样会将其转换回字典。只需执行dict.OrderBy(...)
即可;这将生成所需的枚举器。 - ToolmakerSteve通过观察并利用一些C# 3.0特性,我们可以做到这一点:
foreach (KeyValuePair<string,int> item in keywordCounts.OrderBy(key=> key.Value))
{
// do something with item.Key and item.Value
}
这是我见过的最干净的方式,类似于处理哈希的Ruby方式。
keywordCounts.OrderBy(key => key.Value) select item).ToDictionary(t => t.Key, t => t.Value)
这段代码)只是我答案的一个小补充 :) 顺便说一句,谢谢你 :) - Andrius Naruševičius总的来说,你别无选择,只能遍历整个字典并查看每个值。
也许这个链接会有所帮助: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);
}
);
无论如何,您都无法对字典进行排序。它们实际上并没有被排序。字典的保证是键和值集合是可迭代的,并且可以通过索引或键检索值,但没有任何特定顺序的保证。因此,您需要将名称值对放入列表中。
在词典中,您不需要对条目进行排序。.NET中的Dictionary类是作为散列表实现的 - 根据定义,此数据结构无法进行排序。
如果您需要能够按键迭代您的集合 - 您需要使用SortedDictionary,它是作为二叉搜索树实现的。
然而,在您的情况下,源结构并不重要,因为它已经按不同字段排序了。您仍需要按频率排序并将其放入新集合中,该集合按相关字段(频率)排序。因为许多单词可能具有相同的频率(并且您将将其用作键),所以既不能使用Dictionary也不能使用SortedDictionary(它们需要唯一的键)。这将使您使用SortedList。
我不明白为什么您坚持保留到您的主/第一个字典中的原始项的链接。
如果您的集合中的对象具有更复杂的结构(更多字段)并且您需要能够有效地使用多个不同字段作为键访问/排序它们 - 您可能需要一个自定义数据结构,该数据结构由支持O(1)插入和删除(LinkedList)的主存储器和几个索引结构组成 - Dictionaries/SortedDictionaries/SortedLists。这些索引将使用您复杂类的一个字段作为键,并使用指向LinkedListNode中的指针/引用作为值。
您需要协调插入和删除以使索引与主集合(LinkedList)保持同步,我认为删除操作会非常昂贵。这类似于数据库索引的工作方式 - 它们非常适用于查找,但在需要执行许多插入和删除时它们变得很繁琐。
上述所有内容只有在您要进行大量查找处理时才是合理的。如果您只需要按频率输出它们一次,那么可以只生成一个(匿名)元组列表:
var dict = new SortedDictionary<string, int>();
// ToDo: populate dict
var output = dict.OrderBy(e => e.Value).Select(e => new {frequency = e.Value, word = e.Key}).ToList();
foreach (var entry in output)
{
Console.WriteLine("frequency:{0}, word: {1}",entry.frequency,entry.word);
}
您可以使用:
Dictionary<string, string> dic= new Dictionary<string, string>();
var ordered = dic.OrderBy(x => x.Value);
return ordered.ToDictionary(t => t.Key, t => t.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));
IComparer
来完成此操作(确实它接受要比较的键,但是有了键,您就可以获取值)。;-) - BrainSlugs83ElementAt(int index)
方法。此外,你还可以使用foreach
循环来按索引迭代。 - Barreto