2011-09-14 11 views

Odpowiedz

15

Najprostszym sposobem byłoby prawdopodobnie utworzenie słownika przy użyciu ToDictionary, a następnie wywołanie konstruktora SortedList<TKey, TValue>(dictionary). Ewentualnie dodać własną metodę rozszerzenia:

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

To pozwoli Ci stworzyć SortedList sz anonimowych typów jako wartości:

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

Musisz użyć konstruktora IDictionary więc używać rozszerzenia ToDictionary metoda w zapytaniu linq, a następnie użyj nowego: SortedList(dictionary);

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

Coś jak to działa dobrze

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