Terra Incognita
Terra Incognita

Reputation: 167

Can't add data in SortedList C#

I have simple code, where I want to fill my SortedList with some data from arrays.

namespace Test
{
    class TestClass
    {
        public int ValueInt { get; set; }
        public char ValueChar { get; set; }
    }

    class MainClass
    {
        public static void Main(string[] args)
        {
            int[] arr1 = { 1, 2, 3 };
            char[] arr2 = { 'a', 'b', 'c' };

            SortedList<TestClass, char> list = new SortedList<TestClass, char>();

            for (int i = 0; i < 3; i++)
            {
                list.Add(new TestClass() { ValueInt = arr1[i], ValueChar = arr2[i]}, '+');
            }

            foreach (KeyValuePair<TestClass, char> kvp in list)
            {
                Console.WriteLine(
                "Key1 = {0}, Key2 = {1}, Value = {2}", 
                    kvp.Key.ValueInt, kvp.Key.ValueChar, kvp.Value
                    );
            }
        }
    }
}

Program throw error:

System.InvalidOperationException (Failed to compare two elements in the array)

Program throw it at the point of second iteration of that loop:

list.Add(new TestClass() { ValueInt = arr1[i], ValueChar = arr2[i]}, '+');

HOWEVER, Program works if I change SortedList to Dictionary

How can I make my Program works with the SortedList ?

Upvotes: 2

Views: 62

Answers (1)

vladimir
vladimir

Reputation: 15226

TestClass should implement IComparable-interface.

SortedList requires a comparer implementation to sort and to perform comparisons (see MS docs)

class TestClass : IComparable<TestClass>
{
    public int ValueInt { get; set; }
    public char ValueChar { get; set; }

    public int CompareTo(TestClass other)
    {
        if (ReferenceEquals(this, other)) return 0;
        if (ReferenceEquals(null, other)) return 1;

        var valueIntComparison = ValueInt.CompareTo(other.ValueInt);
        if (valueIntComparison != 0) return valueIntComparison;

        return ValueChar.CompareTo(other.ValueChar);
    }
}

Upvotes: 3

Related Questions