I have a List<> containing object from a class which has a String property that I want to sort using the following rule:
- All objects inside the list which the "code" is
X5should be on top of the list. - All objects inside the list which the "code" is
G2will be after theX5objects. - All objects inside the list which the "code" is
H3will be after theG2objects. - All other object should be at the end of the list, sorted alphabetically by the "code".
I tried some code but kept throwing this exception:
System.ArgumentException: Unable to sort because the IComparer.Compare() method returns inconsistent results. Either a value does not compare equal to itself, or one value repeatedly compared to another value yields different results. IComparer: ''.
Code attempt:
public class myObject: IComparable<myObject>
{
int id { get; set; }
string name { get; set; }
string code { get; set; }
public myObject()
{
}
public int CompareTo(myObject other)
{
//I don't know how to write the sort logic
}
}
Later I would like to create a list of "myObject" and sort it:
List<myObject> objects = new List<myObject>();
objects.Add(new MyObject() { id = 0, name = "JENNIFER"; code = "G2"; });
objects.Add(new MyObject() { id = 1, name = "TOM"; code = "H3"; });
objects.Add(new MyObject() { id = 2, name = "JACK"; code = "G2"; });
objects.Add(new MyObject() { id = 3, name = "SAM"; code = "X5"; });
objects.Sort();
And the list would be in the following order:
- SAM
- JENNIFER
- JACK
- TOM