Search code examples
c#win-universal-appsorteddictionary

Isn't Char IComparable?


When I code in C#, I useSystem.Collections.Generic.SortedDictionary<char,int> in my code. But when I call its Max() method, it throw a exception:

An exception of type 'System.ArgumentException' occurred in mscorlib.ni.dll but was not handled in user code

Additional information: At least one object must implement IComparable.

Doesn't Char implement IComparable? How can I solve it?

Thanks!

Ps: My code is easy:

SortedDictionary<char,int> letter = new SortedDictionary<char,int>;
//some codes
    if (letter.Count != 0) var First = letter.Max();

Solution

  • Max() is an extension method of IEnumerable<T>, and SortedDictionary<TKey, TValue> implement IEnumerable<KeyValuePair<TKey, TValue>>.

    The problem is KeyValuePair<TKey, TValue> isn't IComparable.

    If you want the max key you can use Keys property:

    SortedDictionary<char, int> dict = new SortedDictionary<char, int>();
    ...
    
    var key = dict.Keys.Max();
    var value = dict[key];
    

    EDIT:

    If you want count how many times an char is repeated dont use a SortedDictionary<TKey, Value>, each element added to the collection requires O(log n). At the end, adding process will take O(n log n) operations.

    In your case a simple Dictionary<TKey, TValue> or an array is more suitable:

    var dict = new Dictionary<char, int>();
    
    foreach (char c in chars)
    {
        if (!dict.ContainsKey(c))
            dict[c] = 0;
    
        dict[c]++;
    }
    
    var maxValue = dict.Values.Max();
    var keyValues = dict.Where(kv => kv.Value == maxValue);
    

    In above code, you find the max count and then the characters with that value.