2009-01-16 22 views

Respuesta

40

editar esta respuesta fue antes de la edición; para una respuesta al problema actualizado, vea this reply.

¿Por qué usar LINQ? Hay un constructor para esta:

new SortedDictionary<int, string>(existing); 

Se podría añadir un ToSortedDictionary - pero no me molestaría ...

+0

Bate por 20 segundos – JaredPar

+0

Acabo de darme cuenta de que no hice una copia de respaldo de los corchetes angulares en mi pregunta original. – Guy

+0

Me alegro de que esta es la respuesta aceptada, a pesar de no responder a lo que OP tenía la intención de preguntar. Definitivamente es la respuesta correcta a la pregunta del título. –

8

No se necesita LINQ. SortedDictionary tiene un constructor para hacer la conversión.

public SortedDictionary<TKey,TValue> Convert<TKey,TValue>(Dictionary<TKey,TValue> map) { 
    return new SortedDictionary<TKey,TValue>(map); 
} 
1

No es necesario LINQ, sólo algunos métodos de extensión ingeniosas: uso

public static IDictionary<TKey, TValue> Sort<TKey, TValue>(this IDictionary<TKey, TValue> dictionary) 
{ 
    if(dictionary == null) 
    { 
     throw new ArgumentNullException("dictionary"); 
    } 

    return new SortedDictionary<TKey, TValue>(dictionary); 
} 

public static IDictionary<TKey, TValue> Sort<TKey, TValue>(this IDictionary<TKey, TValue> dictionary, IComparer<TKey> comparer) 
{ 
    if(dictionary == null) 
    { 
     throw new ArgumentNullException("dictionary"); 
    } 

    if(comparer == null) 
    { 
     throw new ArgumentNullException("comparer"); 
    } 

    return new SortedDictionary<TKey, TValue>(dictionary, comparer); 
} 

Ejemplo:

var dictionary = new Dictionary<int, string> 
{ 
    { 1, "one" }, 
    { 2, "two" }, 
    { 0, "zero" } 
}; 

foreach(var pair in dictionary.Sort()) 
{ 
    Console.WriteLine("{0}: {1}", pair.Key, pair.Value); 
} 

// 0: zero 
// 1: one 
// 2: two 
5

Parece como si usted está pidiendo una manera elegante de llevar a Dictionary<TKey,TValue> y conviértalo en SortedDictionary<TValue,TKey> (tenga en cuenta que el valor de Dictionary es ahora la clave del SortedDictionary). No veo ninguna respuesta que aborde eso así que aquí va.

Se puede crear un método de extensión que tiene este aspecto:

static class Extensions 
{ 
    public static Dictionary<TValue, TKey> 
     AsInverted<TKey, TValue>(this Dictionary<TKey, TValue> source) 
    { 
     var inverted = new Dictionary<TValue, TKey>(); 

     foreach (KeyValuePair<TKey, TValue> key in source) 
      inverted.Add(key.Value, key.Key); 

     return inverted; 
    } 
} 

Y el código de aplicación se vería así:

using System; 
using System.Linq; 
using System.Collections.Generic; 

class Program 
{ 
    static void Main() 
    { 
     var dict = new Dictionary<String, Double>(); 
     dict.Add("four", 4); 
     dict.Add("three", 3); 
     dict.Add("two", 2); 
     dict.Add("five", 5); 
     dict.Add("one", 1); 

     var sortedDict = new SortedDictionary<Double, String>(dict.AsInverted()); 
    } 
} 
0

Inversion usando ToDictionary:

public static IDictionary<TValue, TKey> Invert<TKey, TValue>(this IDictionary<TKey, TValue> dictionary) 
{ 
    if(dictionary == null) 
    { 
     throw new ArgumentNullException("dictionary"); 
    } 

    return dictionary.ToDictionary(pair => pair.Value, pair => pair.Key); 
} 

Ejemplo uso:

var dictionary = new Dictionary<string, int> 
{ 
    { "zero", 0 }, 
    { "one", 1 }, 
    { "two", 2 } 
}; 

foreach(var pair in dictionary.Invert()) 
{ 
    Console.WriteLine("{0}: {1}", pair.Key, pair.Value); 
} 

// 0: zero 
// 1: one 
// 2: two 

Ejemplo de inversión y de clasificación (ver mi otra respuesta para la definición de Sort):

var dictionary = new Dictionary<string, int> 
{ 
    { "one", 1 }, 
    { "two", 2 }, 
    { "zero", 0 } 
}; 

foreach(var pair in dictionary.Invert().Sort()) 
{ 
    Console.WriteLine("{0}: {1}", pair.Key, pair.Value); 
} 

// 0: zero 
// 1: one 
// 2: two 
Cuestiones relacionadas