Ale*_*per 3 .net c# linq sortedlist
如果将LINQ Take扩展方法应用于a SortedList<int, int>,如何将结果转换为新的SortedList<int, int>?
从我得到的运行时错误中,Take方法的结果是EnumerablePartition无法转换为SortedList<int, int>
控制台App中的主要方法编译正常,但是在将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();
}
Run Code Online (Sandbox Code Playgroud)
我本来希望该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和Generics相对较新,但是由于提供了出色的答案,我为可读性创建了一种新的扩展方法:
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);
}
}
Run Code Online (Sandbox Code Playgroud)
现在,创建我的候选清单:
var shortlist = list.Take(2).ToSortedList();
Run Code Online (Sandbox Code Playgroud)
我以为上面的东西可能已经可用!
我本来希望Take方法的结果是一个新的SortedList,或者至少可以将其转换为SortedList,因为这是原始类型。
好吧,这种方式不太有效。如果您Take(2)从一袋糖果中得到两个糖果。您不会因为一个原始的糖果装在袋子里而神奇地带了两个糖果在新袋子里。
从技术上讲,该Take方法采用IEnumerable<>任何类型的,并返回IEnumerable<>相同类型的。原始容器类型的信息在此过程中丢失。
现在显然,就像在我们的糖果示例中一样,如果您希望从大袋子中拿出一个小袋子,每个袋子有两个糖果,那么没有人会阻止您重新包装它们。同样在这里。如果需要排序列表,请从结果中创建一个新的排序列表。但这是手动的。
| 归档时间: |
|
| 查看次数: |
78 次 |
| 最近记录: |