如何让 C# 中的 Linq 返回 SortedList
给定一个 IEnumerable
?如果不能,是否可以将 IEnumerable
强制转换或转换为 SortedList
?
最佳答案
最简单的方法可能是使用 ToDictionary
创建字典, 然后调用 SortedList<TKey, TValue>(dictionary)
构造函数。或者,添加您自己的扩展方法:
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;
}
这将允许您创建 SortedList
s 以匿名类型作为值:
var list = people.ToSortedList(p => p.Name,
p => new { p.Name, p.Age });
关于C# Linq 返回排序列表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7410048/