2011-09-14 34 views

回答

15

最簡單的方法可能是使用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; 
} 

這將允許您創建SortedList s的匿名類型的值:

var list = people.ToSortedList(p => p.Name, 
           p => new { p.Name, p.Age }); 
4

您將需要使用IDictionary構造函數,因此使用ToDictionary擴展方法在你的linq查詢上,然後用新的SortedList(dictionary);

eg

var list=new SortedList(query.ToDictionary(q=>q.KeyField,q=>q)); 
0

事情是這樣的作品就好

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));