C#Linq返回SortedList

Ste*_*ven 11 c# linq sortedlist

如何让Cq中的Linq返回SortedList给定的IEnumerable?如果我不能,是否有可能将其IEnumerable转换为SortedList

Jon*_*eet 18

最简单的方法可能是使用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;
}
Run Code Online (Sandbox Code Playgroud)

这将允许您SortedList使用匿名类型创建s作为值:

var list = people.ToSortedList(p => p.Name,
                               p => new { p.Name, p.Age });
Run Code Online (Sandbox Code Playgroud)


Bob*_*ale 5

您将需要使用IDictionary构造函数,因此在 linq 查询上使用ToDictionary扩展方法,然后使用 newSortedList(dictionary);

例如

 var list=new SortedList(query.ToDictionary(q=>q.KeyField,q=>q));
Run Code Online (Sandbox Code Playgroud)