Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to sort a dictionary by key

I have dictionary Dictionary<string, Point>

the Key is c1,c3,c2,t1,,t4,t2 I want to sort them to be c1,c2,c3,t1,t2,t3

I'm trying to sort it using

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

but it doesn't work

any idea how to solve that

like image 572
AMH Avatar asked Nov 13 '11 07:11

AMH


People also ask

Can we sort a dictionary with keys?

Dictionaries are made up of key: value pairs. Thus, they can be sorted by the keys or by the values.

Can you sort dictionaries by key in Python?

To sort dictionary key in python we can use dict. items() and sorted(iterable) method. Dict. items() method returns an object that stores key-value pairs of dictionaries.

How do I sort a list of dictionaries by key?

To sort a list of dictionaries according to the value of the specific key, specify the key parameter of the sort() method or the sorted() function. By specifying a function to be applied to each element of the list, it is sorted according to the result of that function.


2 Answers

Input.OrderBy does not sort the dictionary, it creates a query that returns the items in a specific order.

Perhaps OrderedDictionary gives you what you want.

Or use the Generic SortedDictionary

like image 164
Emond Avatar answered Sep 21 '22 17:09

Emond


Load the unsorted object into a SortedDictionary object like so:

SortedDictionary<string, string> sortedCustomerData = new SortedDictionary<string,string>(unsortedCustomerData); 

Where unsortedCustomerData is the same generic type (Dictionary string, string or in your case string, point). It will automatically sort the new object by key

According to msdn: SortedDictionary(IDictionary): Initializes a new instance of the SortedDictionary class that contains elements copied from the specified IDictionary and uses the default IComparer implementation for the key type.

like image 34
sandman0615 Avatar answered Sep 21 '22 17:09

sandman0615