C#Linq返回SortedList
发布时间:2020-12-16 05:37:46 所属栏目:百科 来源:网络整理
导读:如何让C#中的 Linq返回一个给出IEnumerable的 SortedList ?如果我不能,可以将IEnumerable转换或转换为SortedList吗? 解决方法 最简单的方法可能是使用ToDictionary创建一个字典,然后调用SortedList TKey,TValue(dictionary)构造函数.或者,添加您自己的扩展
如何让C#中的
Linq返回一个给出IEnumerable的
SortedList ?如果我不能,可以将IEnumerable转换或转换为SortedList吗?
解决方法
最简单的方法可能是使用ToDictionary创建一个字典,然后调用SortedList< TKey,TValue>(dictionary)构造函数.或者,添加您自己的扩展方法:
public static SortedList<TKey,TValue> ToSortedList<TSource,TKey,TValue> (this IEnumerable<TSource> source,Func<TSource,TKey> keySelector,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; } 这将允许您使用匿名类型创建SortedLists作为值: var list = people.ToSortedList(p => p.Name,p => new { p.Name,p.Age }); (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |