Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I convert from a Dictionary to a SortedDictionary using LINQ in C#?

How to convert a Dictionary to a SortedDictionary?

In addition to general conversion (preserving types of key and values) I'm interested in swapping the keys and values as part of the conversion: have a Dictionary<string, double> and I want to convert it to a SortedDictionary<double, string>.

How do I do this using LINQ extension methods in C# 3.0?

like image 347
Guy Avatar asked Jan 16 '09 19:01

Guy


People also ask

Can we convert list to dictionary in C#?

Convert List to Dictionary Using the Non-Linq Method in C# We can also convert a list to a dictionary in a non-LINQ way using a loop. It is advised to use the non-LINQ method because it has improved performance, but we can use either method according to our preferences.

Can C# dictionary have different data types?

In Dictionary, key must be unique. Duplicate keys are not allowed if you try to use duplicate key then compiler will throw an exception. In Dictionary, you can only store same types of elements. The capacity of a Dictionary is the number of elements that Dictionary can hold.

How do you sort SortedDictionary?

We can use the OrderBy method to sort a SortedDictionary items. The OrderBy method takes a key name that items will be sorted based on.


1 Answers

Why use LINQ? There is a constructor for this:

new SortedDictionary<int, string>(existing); 

You could add a ToSortedDictionary - but I wouldn't bother...


Note: this is an answer to the title of the question (convert a Dictionary to a SortedDictionary for the same types, if you need additional step that OP is looking for - swap key and values in the process - as shown in the updated problem, see this answer.

like image 146
Marc Gravell Avatar answered Sep 18 '22 11:09

Marc Gravell