I am trying to implement the IComparable
interface in my custom object so that List.Sort()
can sort them alphabetically.
My object has a field called _name
which is a string type, and I want it to sort based on that. Here is the method I implemented:
public int CompareTo(object obj)
{
//Int reference table:
//1 or greater means the current instance occurs after obj
//0 means both elements occur in the same position
//-1 or less means the current instance occurs before obj
if (obj == null)
return 1;
Upgrade otherUpgrade = obj as Upgrade;
if (otherUpgrade != null)
return _name.CompareTo(otherUpgrade.Name);
else
throw new ArgumentException("Passed object is not an Upgrade.");
}
Not sure if I did something wrong or if it's just the way the string CompareTo
works, but basically my List was sorted like this:
- Test Upgrade
- Test Upgrade 10
- Test Upgrade 11
- Test Upgrade 12
- Test Upgrade 13
- Test Upgrade 14
- Test Upgrade 15
- Test Upgrade 2
- Test Upgrade 3
- Test Upgrade 4
- Test Upgrade 5
I want them to be sorted like this:
- Test Upgrade
- Test Upgrade 2
- Test Upgrade 3
- ...etc