我常常具有排字典,包括键的和价值观,通过价值。例如,我有一个对话和各自的频率,我想到为了通过频率。

还有一个 SortedList 这是很好的一个单一的价值(说频率),那我想地图回到这个词。

SortedDictionary 订单的关键,不值。一些度假来了 定义类, 但是有一个更清洁的方式?

有帮助吗?

解决方案

使用:

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

因为你就是目标。网2.0或以上,可以简化这一进lambda法--这是等同的,但短。如果你们的目标。网2.0你只能用这种语法如果使用的编译器Visual Studio2008年(或以上)。

var myList = aDictionary.ToList();

myList.Sort((pair1,pair2) => pair1.Value.CompareTo(pair2.Value));

其他提示

使用皇宫:

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 条款。

var ordered = dict.OrderBy(x => x.Value);

环顾四周,并采用某C#3.0特征,我们可以这样做:

foreach (KeyValuePair<string,int> item in keywordCounts.OrderBy(key=> key.Value))
{ 
    // do something with item.Key and item.Value
}

这是干净的我已经看到类似的红宝石的方式处理的散列。

你可以按一词典的价值并将其重新保存本身(所以,当你foreach了它的价值观出来的顺序):

dict = dict.OrderBy(x => x.Value).ToDictionary(x => x.Key, x => x.Value);

当然,它可能不是正确的,但它的工作。

在一个高水平,你没有其他选择,然后走过整个典和看每个的价值。

也许这有助于:http://bytes.com/forum/thread563638.html 复制/粘贴从约翰Timney:

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

你永远不能排序一词典。他们实际上并没有订购。保证一词典是关键的和价值的集合是迭代和价值观可以检索的索引或钥匙,但是没有保证的任何特定顺序。因此,你会需要得到这个名字值对进入一个清单。

你不排序的条目。词典中类。净是实现为hashtable-这个数据结构不排序通过的定义。

如果你需要能够迭代过你的收集(由关键)的-你需要使用SortedDictionary,这是实现为二进制的搜索树。

在你的情况,但是源的结构是无关紧要的,因为它是由不同的领域。你将仍然需要进行排序它通过频,并把它放在一个新的集合按相关领域(频率)。因此,在这个收集的频率键和词是值。由于许多词可以具有相同的频率(和你打算使用它作为一个关键的)不能使用既不是字典的,也不SortedDictionary(他们需要独特键)。这让你有一个SortedList.

我不明白为什么你坚持要保持一个链接到原来的项目在主要动/第一词典。

如果目的在收集有一个更复杂的结构(更多的领域)并且您必须能够有效地访问/排序,他们使用若干不同领域的钥匙-你可能会需要一定数据结构,将包括的主要储存,支持O(1)插入和删除(链表)和若干索引编制结构的-字典/SortedDictionaries/SortedLists.这些索引将使用的一个领域从你的复杂类为一个关键和指针/参考LinkedListNode的链表作为一个价值。

你会需要协调插入和汇清除量保持你的指数同步主要集(链表)和清除量将是非常昂贵我想象的。这是类似于数据库索引的工作-他们是梦幻般的查找,但是他们成为一个负担,当你需要执行许多insetions和删除。

所有上述只是有道理如果你要做一些看起重处理。如果你只需要输出它们一旦按频率然后你只能产生的列表(匿名)组:

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

或者为了好玩,你可以使用一些皇宫扩展的善良:

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

数值进行排序

这显示出如何进行排序的价值在一词典。我们看到控制台节目可以编制在Visual Studio和运行。它增加了关键的字典和那种他们通过他们的价值观。记得词典的实例是最初没有排序在任何方式。我们使用皇宫排序依据关键词查询中发言。

排序依据的条款 计划这种词典[C#]

using System;
using System.Collections.Generic;
using System.Linq;

class Program
{
    static void Main()
    {
        // Example dictionary.
        var dictionary = new Dictionary<string, int>(5);
        dictionary.Add("cat", 1);
        dictionary.Add("dog", 0);
        dictionary.Add("mouse", 5);
        dictionary.Add("eel", 3);
        dictionary.Add("programmer", 2);

        // Order by values.
        // ... Use LINQ to specify sorting by value.
        var items = from pair in dictionary
                orderby pair.Value ascending
                select pair;

        // Display results.
        foreach (KeyValuePair<string, int> pair in items)
        {
            Console.WriteLine("{0}: {1}", pair.Key, pair.Value);
        }

        // Reverse sort.
        // ... Can be looped over in the same way as above.
        items = from pair in dictionary
        orderby pair.Value descending
        select pair;
    }
}

输出

dog: 0
cat: 1
programmer: 2
eel: 3
mouse: 5

排序 SortedDictionary 列表,以结合成一个 ListView 控制使用VB.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

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

最简单的方式获得排序词典是使用建立在 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 将包含的排版本的 sections

其他的答案是好的,如果你想要的是有一个"临时"排序的列表的价值。但是,如果你想有一个按字典 Key会自动同步 另一个词典,是排序 Value, 你可以用的 Bijection<K1, K2>.

Bijection<K1, K2> 允许你的初始化的收集与两个现有的字典,所以如果你想要一个他们可以分类,并且希望其他人进行排序,可以为你下的双射代码

var dict = new Bijection<Key, Value>(new Dictionary<Key,Value>(), 
                               new SortedDictionary<Value,Key>());

你可以使用 dict 像任何正常的词典(它实现 IDictionary<K, V>),然后叫 dict.Inverse 要获得"反向"的字典是排序 Value.

Bijection<K1, K2> 是的一部分 Loyc.Collections.dll, 但如果你想,你可能仅仅复制 源代码 到你自己的项目。

注意到:在情况有多键用相同的值,则不能使用 Bijection, 但你可以手动同步之间的一个普通的 Dictionary<Key,Value> 和一个 BMultiMap<Value,Key>.

假设我们有一个词

   Dictionary<int, int> dict = new Dictionary<int, int>();
   dict.Add(21,1041);
   dict.Add(213, 1021);
   dict.Add(45, 1081);
   dict.Add(54, 1091);
   dict.Add(3425, 1061);
   sict.Add(768, 1011);

1)可以使用 temporary dictionary to store values as :

        Dictionary<int, int> dctTemp = new Dictionary<int, int>();

        foreach (KeyValuePair<int, int> pair in dict.OrderBy(key => key.Value))
        {
            dctTemp .Add(pair.Key, pair.Value);
        }

实际上在C#、字典力有sort()方法, 因为你更感兴趣的,在排序的价值, 你不能得到价值观直到你为他们提供关键, 在短暂的,你需要迭代他们, 使用皇宫的命令,

var items = new Dictionary<string, int>();
items.Add("cat", 0);
items.Add("dog", 20);
items.Add("bear", 100);
items.Add("lion", 50);

// Call OrderBy method here on each item and provide them the ids.
foreach (var item in items.OrderBy(k => k.Key))
{
    Console.WriteLine(item);// items are in sorted order
}

你可以做一个伎俩,

var sortedDictByOrder = items.OrderBy(v => v.Value);

var sortedKeys = from pair in dictName
            orderby pair.Value ascending
            select pair;

它还取决于什么样的价值观你们储存
它是单(如string,int)或多个(如清单,列、用户定义的类),
如果是单身你可以做清单然后适用于排序。
如果用户定义的类, 然后这类必须实施类,
ClassName: IComparable<ClassName> 和复盖 compareTo(ClassName c) 因为他们更快于皇宫和更多的对象的取向。

你可以排序的字典的价值,并得到的结果在字典中使用的代码如下:

Dictionary <<string, string>> ShareUserNewCopy = 
       ShareUserCopy.OrderBy(x => x.Value).ToDictionary(pair => pair.Key,
                                                        pair => pair.Value);                                          

给你们的字典你可以直接将它们的价值观,使用以下一个衬垫:

var x = (from c in dict orderby c.Value.Order ascending select c).ToDictionary(c => c.Key, c=>c.Value);
许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top