Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using .ToDictionary()

Tags:

c#

generics

I have a method returning a List, let's call it GetSomeStrings().

I have an extension method on string class, returning number of characters in the string, eg. myString.Number('A').

I would like to, in a single line, grab a dictionary. An entry of the dictionary contains the string, and the number of a chosen character in the string.

Actually I do the following:

var myDic = GetSomeStrings().ToDictionary(x=>x.Number('A')); 

which gives me a dictionary <int,string>; I would like the key as the string.

After, I'd like to order the dictionary on the int value. It is possible to include this in the previous statement ?

I'd really like to avoid a collection enumeration to sort or create the dictionary from the list, which is what i do actually without troubles. Thank you for your optimization help !

like image 891
Toto Avatar asked Aug 31 '10 16:08

Toto


People also ask

How does ToDictionary work?

This C# extension method converts a collection into a Dictionary. It works on IEnumerable collections such as arrays and Lists.

What does ToDictionary do?

The ToDictionary method in C# is used to creates a System. Collections. Generic. Dictionary<TKey,TValue> from an System.

What is ToDictionary C#?

The ToDictionary method is an extension method in C# and converts a collection into Dictionary. Firstly, create a string array − string[] str = new string[] {"Car", "Bus", "Bicycle"}; Now, use the Dictionary method to convert a collection to Dictionary − str.ToDictionary(item => item, item => true);

What is ToDictionary in LINQ C#?

In LINQ, ToDictionary() Method is used to convert the items of list/collection(IEnumerable<T>) to new dictionary object (Dictionary<TKey,TValue>) and it will optimize the list/collection items by required values only.


2 Answers

Edit

The ToDictionary() method has an overload that takes two lambda expressions (nitpick: delegates); one for the key and one for the value.

For example:

var myDic = GetSomeStrings().ToDictionary(x => x, x => x.Number('A')); 

Note that the values returned by GetSomeStrings() must be unique.


.Net's Dictionary<TKey, TValue> is unordered; it cannot be sorted at all.

Instead, you can sort the dictionary when you use it, like this:

foreach(KeyValuePair<string, int> kvp in dict.OrderBy(kvp => kvp.Value)) 
like image 113
SLaks Avatar answered Sep 29 '22 10:09

SLaks


A regular Dictionary is not sorted, but you can use a SortedDictionary:

var sortedDict = new SortedDictionary<string, int>(     GetSomeStrings().ToDictionary(x => x, y => y.Number('A'))); 

That should give you a SortedDictionary<string, int> sorted by the string key.

like image 26
Justin Niessner Avatar answered Sep 29 '22 11:09

Justin Niessner