2009-08-09 8 views

risposta

10

SortedList è ottimizzato in modo che le inerenze si verificano in modo ordinato, in modo tale che l'enumerazione si verifichi in un ordine ordinato al minimo costo. Qualsiasi altra cosa richiede un ri-ordinamento. Così:

 SortedList<string,bool> l=new SortedList<string, bool>(); 
     l.Add("a",true); 
     l.Add("a",false); 
     l.Add("b",true); 
     l.Add("b",false); 
     var orderByVal=l.OrderBy(kvp => kvp.Value); 

ma questa enumerazione sarà notevolmente più lento per calcolare ed essere attuate up-front, che richiede capacità di archiviazione di farlo.

A seconda della situazione, potrebbe essere più economico mantenere 2 istanze SortedList con la chiave/il valore invertito.

+1

Non è possibile aggiungere lo stesso elemento alla lista due volte. Genera un'eccezione –

+0

@BradPatton Sì, hai ragione ... – spender

2

In .NET 2.0, è possibile aggiungere i tuoi oggetti a un SortedList:

public static List<MyObject> SortedObjects(IEnumerable<MyObject> myList) { 
    SortedList<string, MyObject> sortedList = new SortedList<string, MyObject>(); 
    foreach (MyObject object in myList) { 
     sortedList.Add(object.ValueIWantToSort, object); 
    } 

    return new List<MyObject>(sortedList.Values); 
    } 
+0

Il problema con questa implementazione è che il valore che vuoi ordinare potrebbe non essere univoco come nella domanda dell'OP. –

3

Per scendere tutti gli elementi della lista

list.OrderByDescending(); 

o

var list = list.OrderByDescending(x => x.Product.Name) 
        .ThenBy(x => x.Product.Price).ToList(); 
+0

riguarda la lista ordinata, non la lista – Kevman

0

Normalmente che ordinati dalla prima chiave della lista quindi se scambi la chiave e il valore sull'aggiunta, allora ma tch che sul legame quell'esempio campione io uso e funzionano bene

public static SortedList<string, string> GetCountries(string conn) 
     { 
      var dict = new SortedList<string, string>(); 
      dict.Add("","Select One"); 
      var sql = "SELECT [CountryID]  ,[Descr] FROM [dbo].[Countries] Order By CountryID "; 
      using (var rd = GetDataReader(conn, sql)) 
      { 
       while (rd.Read()) 
       { 
        dict.Add(rd["Descr"].ToString(), rd["CountryID"].ToString()); 
       } 
      } 
      return dict; 
     } 

Dim List As SortedList(Of String, String) = VDB.CoreLib.DbUtils.GetCountries(connDB) 

     ddlBankCountry.DataSource = List 
     ddlBankCountry.DataTextField = "Key" 
     ddlBankCountry.DataValueField = "Value" 
     ddlBankCountry.DataBind()