2011-09-14 10 views

Respuesta

15

La manera más simple probablemente sería crear un diccionario usando ToDictionary, y luego llamar al constructor SortedList<TKey, TValue>(dictionary). Alternativamente, añadir su propio método de extensión:

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

Esto le permitirá crear SortedList s con los tipos anónimos como los valores:

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

Usted tendrá que utilizar el constructor IDictionary a fin de utilizar la extensión ToDictionary método en su consulta linq y luego use el nuevo SortedList(dictionary);

por ej.

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

Algo como esto funciona bien

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