Reputation: 22340
using System.Collections.Generic;
Suppose I have an IEnumerable<KeyValuePair<TKey, TValue>>
(possibly an IReadOnlyDictionary<TKey, TValue>
, or perhaps the result of a LINQ method chain) and I want to construct a SortedDictionary<TKey, TValue>
from it. SortedDictionary
has 4 constructors:
public SortedDictionary();
public SortedDictionary(IComparer<TKey>? comparer);
public SortedDictionary(IDictionary<TKey, TValue> dictionary);
public SortedDictionary(IDictionary<TKey, TValue> dictionary, IComparer<TKey>? comparer);
If I had an IDictionary<TKey, TValue>
then it would be clear what I should do. But since I have an
IEnumerable<KeyValuePair<TKey, TValue>>
instead, there are two approaches I could take.
Dictionary<TKey, TValue>
using LINQ's ToDictionary()
, and pass that to one of the SortedDictionary
constructors that accepts an IDictionary
. This has the advantage that I will write less code.SortedDictionary
and loop through the KeyValuePairs
in my IEnumerable
, adding them to the dictionary. This has the advantage that I don't construct a whole dictionary just for the sake of feeding it to the SortedDictionary
constructor. But is that important? Is there any performance advantage? Does it depend on whether the KeyValuePairs
in my IEnumerable
are sorted (with respect to the IComparer<TKey>
my SortedDictionary
will use) or in random order?What if I wanted to create a SortedList<TKey, TValue>
instead of a SortedDictionary
? Would the answer be the same?
Upvotes: 1
Views: 646
Reputation: 117064
I feel like you're over thinking this. Wouldn't this suffice?
var dictionary = new SortedDictionary<TKey, TValue>();
foreach (var pair in pairs)
{
dictionary.Add(pair.Key, pair.Value);
}
Or, if you prefer, wrap it in an extension method:
public static SortedDictionary<K, V> ToSortedDictionary<K, V>(this IEnumerable<KeyValuePair<K, V>> pairs)
{
var dictionary = new SortedDictionary<K, V>();
foreach (var pair in pairs)
{
dictionary.Add(pair.Key, pair.Value);
}
return dictionary;
}
Then it's just:
SortedDictionary<TKey, TValue> dictionary = pairs.ToSortedDictionary();
Upvotes: 2