【发布时间】:2011-09-14 00:34:04
【问题描述】:
在给定IEnumerable 的情况下,如何让C# 中的Linq 返回SortedList?如果我不能,是否可以将IEnumerable 转换或转换为SortedList?
【问题讨论】:
标签: c# linq sortedlist
在给定IEnumerable 的情况下,如何让C# 中的Linq 返回SortedList?如果我不能,是否可以将IEnumerable 转换或转换为SortedList?
【问题讨论】:
标签: c# linq 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;
}
这将允许您使用匿名类型作为值创建SortedLists:
var list = people.ToSortedList(p => p.Name,
p => new { p.Name, p.Age });
【讨论】:
您将需要使用 IDictionary 构造函数,因此在 linq 查询中使用 ToDictionary 扩展方法,然后使用新的 SortedList(dictionary);
例如
var list=new SortedList(query.ToDictionary(q=>q.KeyField,q=>q));
【讨论】:
这样的东西很好用
List<MyEntity> list = DataSource.GetList<MyEntity>(); // whatever data you need to get
SortedList<string, string> retList = new SortedList<string, string> ();
list.ForEach ( item => retList.Add ( item.IdField, item.Description ) );
【讨论】: