开发者

c# sorting a StringDictionary by value, NOT key

What is the 'best' way to sort (or iterate) over a StringDictionary in order of Value (not Key)

E.g. Key - Value

  • 1 - X label
  • 2 - A label
  • 3 - Other label

would give

  • 2 - A label
  • 3 - Other label
  • 1 - X label

EDIT开发者_JAVA技巧 - I meant to say "using .NET 2.0 features". Sorry, me bad...


Use LINQ:

var items = from k in d.Keys
                    orderby d[k] ascending
                    select k;

If you are restricted to C# 2.0 features, use this:

    IDictionary<string, string> d = new Dictionary<string, string>();
    d["1"] = "X label";
    d["2"] = "A label";
    d["3"] = "Other Label";

    List<KeyValuePair<string, string>> myList = new List<KeyValuePair<string, string>>(d);
    myList.Sort(
        delegate(KeyValuePair<string, string> a,
        KeyValuePair<string, string> b)
        {
            return a.Value.CompareTo(b.Value);
        }
    );

Note: If you are using a StringDictionary instead of Dictionary, check out Anthony's solution.


Using the StringDictionary class, here is a method to use LINQ's OrderBy. Assumes you have .NET 3.5.

var sortedDictionary = dictionary.Cast<DictionaryEntry>().OrderBy(pair => pair.Value);

Using 2.0, it's a bit trickier. Here's an approach using a Comparison delegate.

StringDictionary dictionary = new StringDictionary();
dictionary.Add("1", "One");
dictionary.Add("2", "Two");
dictionary.Add("3", "Three");

DictionaryEntry[] sortedDictionary = new DictionaryEntry[dictionary.Count];
dictionary.CopyTo(sortedDictionary, 0);
Comparison<DictionaryEntry> comparison = new Comparison<DictionaryEntry>(delegate (DictionaryEntry obj1, DictionaryEntry obj2) { return ((string)obj1.Value).CompareTo((string)obj2.Value); });
Array.Sort(sortedDictionary, comparison);

So the actual sort would be in the sortedDictionary array.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜