Convert dictionary to List<KeyValuePair>

72,745

Solution 1

To convert a Dictionary<TKey, TValue> to a List<KeyValuePair<TKey, TValue>> you can just say

var list = dictionary.ToList();

or the more verbose

var list = dictionary.ToList<KeyValuePair<TKey, TValue>>();

This is because Dictionary<TKey, TValue> implements IEnumerable<KeyValuePair<TKey, TValue>>.

Solution 2

Using linq:

myDict.ToList<KeyValuePair<double, double>>();

Dictionary elements are KeyValuePair items.

Solution 3

Like Jason said. But if you don't really need a list, then you can just cast it to an ICollection<TKey, TValue>; because it implements this interface, but some parts only explicitly. This method performs better because it don't copy the entire list, just reuses the same dictionary instance.

Share:
72,745
Sean
Author by

Sean

Updated on July 09, 2022

Comments

  • Sean
    Sean almost 2 years

    I know that its possible to convert a List of KeyValuePair into a Dictionary, but is there a quick way (besides looping through manually) to perform the vice versa operation?

    This would be the manual way,

    foreach (KeyValuePair<double,double> p in dict)
    {
        list.Add(new KeyValuePair<double,double>(p.Key,p.Value));
    }
    

    Not really that bad but I was just curious.

  • jason
    jason over 13 years
    ToList merely copies the references to the dictionary items. This is blazingly fast and highly unlikely to be a relevant performance issue.
  • fejesjoco
    fejesjoco over 13 years
    Casting is infinitely faster. Which isn't noticeable if you do it only a few times with small lists, but still, it does matter a lot.
  • JBSnorro
    JBSnorro over 13 years
    @Jason: Not true. A call to the extensionmethod Enumerable.ToList<KeyValuePair<TKey, TValue>> is potentially expensive. From another perspective, it must return a new list, otherwise you could add items to the dictionary by adding items to the list, which would be weird.
  • jason
    jason over 13 years
    @JBSnorro: I don't know what you're talking about. Creating a new list and copying references is cheap.
  • fejesjoco
    fejesjoco over 13 years
    @Jason: and casting is effectively zero compared to that.
  • jason
    jason over 13 years
    @fejesjoco: That's a micro-optimization as performance is almost surely completely irrelevant here.
  • fejesjoco
    fejesjoco over 13 years
    Why do people keep calling these things unnecessary micro-optimizations? How do you know he won't run it a thousand times with lists that contain a million elements? Isn't it always better to learn and do things the best possible way? Is it better if he learns software programming while not giving a * about these things? Well, not my problem, this way I know I'll always have a job.
  • jason
    jason over 13 years
    @fejesjoco: I feel a rant coming on.
  • jason
    jason over 13 years
    @fejesjoco: Because people are enslaved to cycles and bytes like it's still 1980. There is in general too much emphasis on performance first over clarity of code and other concerns. Performance isn't the be all end all anymore (with mobile devices, for example, we should optimize for power consumption, not performance!) I don't know that he won't run it a thousand times with lists that contain a million elements, but I suspect that he won't be. And if he is, I still doubt it matters. And even if it does matter, he's got bigger issues to worry about because he's doing something wrong.
  • jason
    jason over 13 years
    @fejesjoco: This is a micro-optimization. Period. If it matters, something is seriously wrong with big upfront design stuff.
  • phoog
    phoog over 13 years
    @Jason: KeyValuePair is a struct, so you're only copying references if your keys or values are reference types. Otherwise, you're copying values. And the original example uses value types.
  • jason
    jason over 13 years
    @phoog: First, he's using double. Copying doubles is ridiculously fast. Second, if he's using a value type where copying speed becomes relevant, something is probably wrong.
  • phoog
    phoog over 13 years
    @Jason, I didn't mean to take issue with your statement that the copying in ToList() is blazingly fast. I just meant to point out that KeyValuePair is a value type, not a class.
  • surfasb
    surfasb almost 13 years
    I like Jason's answer. The big picture is always more important. And the big picture isn't necessarily performance.
  • Harry
    Harry almost 11 years
    It may be worth noting that you have to add System.Linq; as a using.
  • BrainSlugs83
    BrainSlugs83 almost 10 years
    You guys are talking about this optimization like it's unreadable or somehow less powerful or something, that's ridiculous. If all you need is a collection, this works great and is the preferred approach, you do not sacrifice any readability and it is infinitely faster (in the few edge cases where that might matter). This is not an unnecessary micro-optimization, it's just good practice. OTOH, If you need a list, take the hit and call .ToList(); -- Either way, your code is easy to read, and probably about as fast as it can be without sacrificing readability.
  • mireazma
    mireazma over 3 years
    These days cycles are almost free. The argument of "performance not being an issue anymore" made them even came up with game and render engines based on C#. AAA games may still incur millions of objects at 60-90 fps. This poses a challenge even with C/C++. C#/.NET was built with the advantage of ease and clarity over C++ at the cost of performance and it's ok, since C# was not meant for AAA games in the first place. So C#/games mix as uninspired, is enough justification for any available optimization. Please, don't condemn optimizations, let the users decide for themselves.