Задайте вопросЗадайте вопрос
 

ОтвеченоC# 2.0: Sorting a Hashtable by Values

Ответы

  • 8 июня 2007 г. 22:05OmegaManMVP, МодераторМедали пользователяМедали пользователяМедали пользователяМедали пользователяМедали пользователя
     Отвечено
     bruno_1 wrote:
    Dictionary<> is worst than Hashtable for sorting, because they don't even bother themself by putting the IComparer interface for comparing.


    Well yes and no, HashTable had to be the swiss army knife of operations. Dictionary is leaner. A dictionary is only for storing values with a key...there is no need to sort the whole thing...just its keys or values....

    The keys and values can be viewed as List<t>. The List<t> is created from the ICollection returned by the exposed properties on the Dictionary of Keys/Values.

    Here I extract the values, I could have done the keys, and sorted them.

    Code Snippet

    Dictionary<int, string> myDict = new Dictionary<int, string>();
    myDict.Add(2, "This");
    myDict.Add(1, "is");
    myDict.Add(5, "radio");
    myDict.Add(4, "clash");

    List<string> song = new List<string>(myDict.Values);
    song.Sort();

    // This writes out: "clash is radio This"
    Console.WriteLine(string.Join(" ", song.ToArray()));


  • 9 июня 2007 г. 20:04nobugzMVP, МодераторМедали пользователяМедали пользователяМедали пользователяМедали пользователяМедали пользователя
     Отвечено
    System.Collections.Generic.SortedDictionary would be the logical choice.  One of its constructors takes an IComparer<T> as its argument.  Yell if you need sample code.

Все ответы