2017-05-09 48 views
0

后的值后的字典我有一个排序的字典一个问题:排序的关键

SortedDictionary<string, List<int>> mySortedDictionary; 

我想创建一个新的Dictionary<string,List<int>>与mySortedDictionary,这是按值排序的数据(完全按项目数列表换句话说就是List.Count)升序,而lists.Count是相同的,按键按字母顺序升序排列。任何人都可以给我一个想法如何做到这一点?

mySortedDictionary.Add("orange", List<2,9>) //List.Count = 2 
mySortedDictionary.Add("money", List<2,4,8,9>) //4 
mySortedDictionary.Add("monkey", List<2,4,9>) //3 
mySortedDictionary.Add("hokey", List<2,5,9>) //3 

//result: order in new sorted Dictionary// 
"orange", List<2,9> 
"hokey", List<2,5,9> 
"monkey", List<2,4,9> 
"money", List<2,4,8,9> 

预先感谢您的帮助!

+0

字典本身没有任何订单。即使你想出了一种按特定顺序插入到字典中的算法,也不能保证你能以相同的顺序重新获得它们。 – Partha

+0

@Partha'SortedDictionary'有一个命令('key') –

回答

0

SortedDictionary门店超过key排序数据,这是内在的,即它不能由一个自定义代替,从而rting。所以如果你想要一个类似于Dictionary的界面,你将不得不构建一个自定义的数据结构。

如果读有序操作中的数据会经常发生,你需要设计一个机制来存储已排序的数据(分别缓存排序的数据和原始数据),或者将数据存储在一个有序的方式。请记住,字典中的Value可能会在数据结构的生命周期中更改,因此您可能需要重新排序数据。这可能不是一个简单的练习。

但是,如果你真的想要一个一般的接口,但有时需要按特定顺序获得数据,那么下面的方法将会有所帮助。

存放在常规Dictionary数据。要按排序顺序获取Dictionary数据,可以提供如下所示的方法。

IOrderedEnumerable<KeyValuePair<string, List<int>>> GetSortedData() { 
    return mySortedDictionary.OrderBy(item => item.Value.Count).ThenBy(item => item.Key); 
} 
+0

非常感谢!!!我正是这个意思。现在我的应用程序按原样工作。 – garm

0

我相信SortedDictionary类型只能在key部分(这是您的要求的一部分)上排序,但您也可以使用OrderBy()方法来指定自定义排序。请注意,这不会更改字典中元素的顺序,而是会返回具有指定顺序的IOrderedEnumerable。因此,如果您想更改订单,则必须重新将字典分配给OrderBy呼叫的结果。如果这是你想要做什么,也许这将帮助:

var mySortedDictionary = new SortedDictionary<string, List<int>> 
{ 
    {"orange", new List<int> {2, 9}}, 
    {"money", new List<int> {2, 4, 8, 9}}, 
    {"monkey", new List<int> {2, 4, 9}}, 
    {"hokey", new List<int> {2, 5, 9}} 
}; 

foreach (var item in mySortedDictionary.OrderBy(item => item.Value.Count)) 
{ 
    Console.WriteLine($"{item.Key} {string.Join(", ", item.Value)}"); 
} 

输出:

enter image description here

为了保持秩序的字典,你就必须做一个重新分配,像所以:

mySortedDictionary = mySortedDictionary.OrderBy(item => item.Value.Count); 
0

你需要一个定制的类来实现IComparable这样的排序是只要你想使用SortedDictionary

public class ncKey : IComparable { 
    public int count; 
    public string name; 

    public int CompareTo(object other) { 
     var b = other as ncKey; 
     var ans1 = count.CompareTo(b?.count); 
     return (ans1 == 0) ? name.CompareTo(b?.name) : ans1; 
    } 
} 

现在你可以使用这个类有一个正确分类词典:

var newSD = new SortedDictionary<ncKey, List<int>>(); 

foreach (var kv in origSD) 
    newSD.Add(new ncKey { count = kv.Value.Count(), name = kv.Key }, kv.Value); 

当然,我不知道如果你真的不会有SortedList,为什么你正在使用的字典更好在所有。