How can I get Linq in C# to return a SortedList
given an IEnumerable
? If I can't, is it possible to cast or transform the IEnumerable
to a SortedList
?
The simplest way would probably be to create a dictionary using ToDictionary
, and then call the SortedList<TKey, TValue>(dictionary)
constructor. Alternatively, add your own extension method:
public static SortedList<TKey, TValue> ToSortedList<TSource, TKey, TValue>
(this IEnumerable<TSource> source,
Func<TSource, TKey> keySelector,
Func<TSource, TValue> valueSelector)
{
// Argument checks elided
SortedList<TKey, TValue> ret = new SortedList<TKey, TValue>();
foreach (var item in source)
{
// Will throw if the key already exists
ret.Add(keySelector(item), valueSelector(item));
}
return ret;
}
This will allow you to create SortedList
s with anonymous types as the values:
var list = people.ToSortedList(p => p.Name,
p => new { p.Name, p.Age });
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With