How to sort a dictionary by key
How to sort a dictionary by key
I have dictionary Dictionary
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
Answer by Beth Whitezel for How to sort a dictionary by key
Just a guess but it looks like you are assuming it is going to sort Input. The OrderBy method actually returns an ordered instance of an IOrderedEnumerable containing the same values. If you want to keep the return value you can do the below:
IOrderedEnumerable orderedInput orderedInput = Input.OrderBy(key=>key.Key)
Most methods that would modify the collection follow this same pattern. It does this so that it is not changing the origional collection instance. This protects you from accidently changing the instance when you didn't intend to. If you do want to only use the sorted instance then you just set the variable to the return of the method as shown above.
Answer by Erno de Weerd for How to sort a dictionary by key
Input.OrderBy
does not sort the dictionary, it creates a query that returns the items in an ordered order.
Perhaps OrderedDictionary gives you what you want.
Or use the Generic SortedDictionary
Answer by AMH for How to sort a dictionary by key
I used
var l = Input.OrderBy(key => key.Key);
and I converted it to Dictionary
Answer by DeveloperX for How to sort a dictionary by key
ok check this it should work
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();
Answer by sandman0615 for How to sort a dictionary by key
Load the unsorted object into a SortedDictionary object like so:
SortedDictionary sortedCustomerData = new SortedDictionary(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.
Fatal error: Call to a member function getElementsByTagName() on a non-object in D:\XAMPP INSTALLASTION\xampp\htdocs\endunpratama9i\www-stackoverflow-info-proses.php on line 71
0 comments:
Post a Comment