如何按键对字典进行排序

我有字典Dictionary

键是c1,c3,c2,t1,t4,t2我想将它们排序为c1,c2,c3,t1,t2,t3

我正在尝试使用它进行排序

 Input.OrderBy(key => key.Key ); 

但它不起作用

任何想法如何解决这个问题

好吧检查一下它应该工作

 var r = new Dictionary(); r.Add("c3", new Point(0, 0)); r.Add("c1", new Point(0, 0)); r.Add("t3", new Point(0, 0)); r.Add("c4", new Point(0, 0)); r.Add("c2", new Point(0, 0)); r.Add("t1", new Point(0, 0)); r.Add("t2", new Point(0, 0)); var l = r.OrderBy(key => key.Key); var dic = l.ToDictionary((keyItem) => keyItem.Key, (valueItem) => valueItem.Value); foreach (var item in dic) { Console.WriteLine(item.Key); } Console.ReadLine(); 

Input.OrderBy不对字典进行排序,它创建一个按订单顺序返回项目的查询。

也许OrderedDictionary可以为您提供所需的内容。

或使用Generic SortedDictionary

将未排序的对象加载到SortedDictionary对象中,如下所示:

 SortedDictionary sortedCustomerData = new SortedDictionary(unsortedCustomerData); 

其中unsortedCustomerData是相同的generics类型(Dictionary字符串,字符串或在您的case字符串中,指向)。 它将按键自动对新对象进行排序

根据msdn:SortedDictionary(IDictionary):初始化SortedDictionary类的新实例,该实例包含从指定的IDictionary复制的元素,并使用默认的IComparer实现作为键类型。

只是一个猜测,但看起来你假设它将排序输入。 OrderBy方法实际上返回包含相同值的IOrderedEnumerable的有序实例。 如果您想保留返回值,可以执行以下操作:

 IOrderedEnumerable orderedInput orderedInput = Input.OrderBy(key=>key.Key) 

大多数修改集合的方法都遵循相同的模式。 它这样做是为了不改变原始集合实例。 这可以防止您在不打算时意外更改实例。 如果您确实只想使用已排序的实例,那么您只需将变量设置为方法的返回值,如上所示。

由于Input.OrderBy创建了一个以有序顺序返回项目的查询,因此只需将其分配给同一个字典即可。

objectDict = objectDict.OrderBy(obj => obj.Key).ToDictionary(obj => obj.Key, obj => obj.Value);

以下代码使用另外两个列表来对字典进行排序 。

 using System; using System.Collections.Generic; using System.Drawing; namespace ConsoleApplication1 { class Program { static void Main(string[] args) { Dictionary r=new Dictionary(); r.Add("c3",new Point(0,1)); r.Add("c1",new Point(1,2)); r.Add("t3",new Point(2,3)); r.Add("c4",new Point(3,4)); r.Add("c2",new Point(4,5)); r.Add("t1",new Point(5,6)); r.Add("t2",new Point(6,7)); // Create a list of keys List zlk=new List(r.Keys); // and then sort it. zlk.Sort(); List zlv=new List(); // Readd with the order. foreach(var item in zlk) { zlv.Add(r[item]); } r.Clear(); for(int i=0;i 

上面代码的输出如下所示。

 c1 1 2 c2 4 5 c3 0 1 c4 3 4 t1 5 6 t2 6 7 t3 2 3 

我用了

 var l = Input.OrderBy(key => key.Key); 

我把它转换成了字典