I have a collection of objects I need to order but not sure how.
There is a string property called, say Prop1, that I want to sort by. And I want to sort based on a List of strings which contain all possible values of Prop1.
List<string> precedence = new List<string>() { "firstPrecedence", "secondPrecedence" ....
How would I implement my CompareTo(object obj) method?
I’m trying with this but don’t really know what i’m doing!
public int CompareTo(object obj)
{
List<string> precedence = new List<string>() { "firstPrecedence", "secondPrecedence", "thirdPrecedence" };
Filter filterOther = obj as Filter;
foreach (var item in precedence)
{
return String.Compare(filterOther.FilterValue, item);
}
return 0;
}
Well, if your precedence list is known at compile time and you can use it, then you can compare the indexes of the values you are sorting:
If the
FilterValuevalue is not in the list,IndexOfwill return -1, which will still work in the sorting implementation here, but may sort at the top or bottom of the list… I can never remember which!Note that the
CompareTomethod returns either 0, something less than 0, or something greater than 0. Usually, -1, 0, and 1.Also, there is a generic
IComparable<>which will allow you to achieve this in a more strongly-typed way:And I’m sure some clever person will give you a solution in LINQ…