C# Linq Result ToDictionary Help

13,384

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.

Share:
13,384
Simpleton
Author by

Simpleton

Updated on June 04, 2022

Comments

  • Simpleton
    Simpleton almost 2 years

    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>);
    
  • dave heywood
    dave heywood almost 11 years
    Lol, I love how complicated some of my code gets, and then 5 seconds on SO and it's 1/10th of the size.... so simple
  • Viku
    Viku over 10 years
    key is not listing after typing r.