【发布时间】:2019-04-18 11:19:38
【问题描述】:
如果我将 LINQ Take 扩展方法应用于 SortedList<int, int>,如何将结果转换为新的 SortedList<int, int>?
从我得到的运行时错误来看,Take 方法的结果是 EnumerablePartition,它不能转换为 SortedList<int, int>
console App中的Main方法编译OK,但是在将list.Take(2)的结果转换为SortedList时在运行时抛出错误
static void Main(string[] args)
{
Console.WriteLine("List");
var list = new SortedList<int, int>();
list.Add(2, 10);
list.Add(8, 9);
list.Add(3, 15);
foreach (KeyValuePair<int, int> item in list){
Console.WriteLine(item.Value);
};
Console.WriteLine("Short List");
var shortlist = (SortedList<int, int>)list.Take(2);
foreach (KeyValuePair<int, int> item in shortlist)
{
Console.WriteLine(item.Value);
};
Console.Read();
}
我本来希望Take 方法的结果是一个新的SortedList<int, int>,或者至少可以转换为SortedList<int, int>,因为这是原始类型。
这是我得到的运行时错误:
Unable to cast object of type 'EnumerablePartition`1[System.Collections.Generic.KeyValuePair`2[System.Int32,System.Int32]]' to type 'System.Collections.Generic.SortedList`2[System.Int32,System.Int32]'
编辑:
我对 LINQ 和泛型比较陌生,但由于提供了出色的答案,我创建了一种新的扩展方法以提高可读性:
static class Extensions {
public static SortedList<TKey, TValue> ToSortedList<TKey, TValue>(this IEnumerable<KeyValuePair<TKey, TValue>> collection)
{
var dictionary = collection.ToDictionary(kvp => kvp.Key, kvp => kvp.Value);
return new SortedList<TKey, TValue>(dictionary);
}
}
现在,创建我的候选名单:
var shortlist = list.Take(2).ToSortedList();
我在想像上面这样的东西可能已经可用了!
【问题讨论】:
标签: c# .net linq sortedlist