Hammerite
Hammerite

Reputation: 22340

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.

What if I wanted to create a SortedList<TKey, TValue> instead of a SortedDictionary? Would the answer be the same?

Upvotes: 1

Views: 646

Answers (1)

Enigmativity
Enigmativity

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

Related Questions