Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C# Linq Result ToDictionary Help

I have a lambda expression that gets results from a Dictionary.

var sortedDict = (from entry in dctMetrics 
                  orderby entry.Value descending 
                  select entry);

The expression pulls back the pairs I need, I can see them in the IDE's debug mode.

How do I convert this back a dictionary of the same type as the source? I know sortedDict's TElement is a KeyValuePair, but I am having trouble fully understanding the ToDictionary extension method's syntax. I also tried foreach'ing the var result to piecewise construct a new dictionary, but to no avail.

Is there something like this (functionality wise):

var results = (from entry in dictionary 
               orderby entry.Value descending 
               select entry);
Dictionary<string,float> newDictionary = results as (Dictionary<string,float>);
like image 877
Simpleton Avatar asked Dec 28 '09 17:12

Simpleton


People also ask

What C is used for?

C programming language is a machine-independent programming language that is mainly used to create many types of applications and operating systems such as Windows, and other complicated programs such as the Oracle database, Git, Python interpreter, and games and is considered a programming foundation in the process of ...

Is C language easy?

Compared to other languages—like Java, PHP, or C#—C is a relatively simple language to learn for anyone just starting to learn computer programming because of its limited number of keywords.

What is C in C language?

What is C? C is a general-purpose programming language created by Dennis Ritchie at the Bell Laboratories in 1972. It is a very popular language, despite being old. C is strongly associated with UNIX, as it was developed to write the UNIX operating system.

What is C full form?

Full form of C is “COMPILE”. One thing which was missing in C language was further added to C++ that is 'the concept of CLASSES'.


1 Answers

You can do it like this:

var newDictionary = results.ToDictionary(r => r.Key, r => r.Value);

Read that as "for each pair in results, add that element to the new dictionary, where the key will be produced as the key of the pair, and the value will be produced as the value of the pair."

Also, just based on your sample code -- you should keep in mind that a Dictionary<T, U> is implemented as a hash table, so it won't maintain the order of the elements you put into it. Consider using a SortedDictionary or a SortedList instead if you need an ordered map.

like image 130
mqp Avatar answered Sep 29 '22 15:09

mqp