简体   繁体   中英

How should I construct a SortedDictionary<TKey, TValue> from an IEnumerable<KeyValuePair<TKey, TValue>>?

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.

  • I could create a 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.
  • I could create an empty 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?

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();

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM