Colin

Colin

  • NA
  • 104
  • 92.3k

Custom SortedList key type

Dec 17 2008 8:40 AM

I have the following code I am writing just to learn generic collections and for some reason it fails to compare when adding a second element to my sorted list.  You'll see I perform a manual comparison at the top of my code and this is successful.  I have implemented IComparer with the accompanying Int Compare() method.  Any ideas where I am going wrong?

using System;

using System.Collections.Generic;

using System.ComponentModel;

using System.Data;

using System.Drawing;

using System.Text;

using System.Windows.Forms;

namespace WindowsApplication2

{

public partial class Form1 : Form

{

public Form1()

{

InitializeComponent();

}

private void Form1_Load(object sender, EventArgs e)

{

SortedList<KeyClass, string> mySortedList = new SortedList<KeyClass, string>();

//This works

#region working comparison code

KeyClass test1 = "E";

Console.WriteLine(test1.MyTestData);

KeyClass test2 = "A";

Console.WriteLine(test2.MyTestData);

Console.WriteLine(test1.Compare(test1, test2).ToString());

#endregion

//This throws a cannot compare elements style exception

//when adding the second element

#region not working

mySortedList.Add("E", "five");

mySortedList.Add("A", "one");

mySortedList.Add("C", "three");

mySortedList.Add("F", "six");

mySortedList.Add("B", "two");

mySortedList.Add("D", "four");

foreach (string myValue in mySortedList.Values) Console.WriteLine(myValue);

#endregion

}

}

//My Custom key class

public struct KeyClass : IComparer<KeyClass>

{

private string myTestData;

public string MyTestData { get { return myTestData; } }

public KeyClass(string myTestData) { this.myTestData = myTestData; }

public int Compare(KeyClass Class1, KeyClass Class2)

{

return string.Compare(Class1.MyTestData, Class2.MyTestData);

}

public static implicit operator KeyClass(string s) { return new KeyClass(s); }

public static implicit operator string(KeyClass k) { return k.MyTestData; }

}

}


Answers (1)