To answer this question for people wishing to use Linq the solution would be:
IEnumerable<string> words = new [] {"foo", "bar"};
words = words.OrderBy(x => x, new MySorter());
Note therefore that you should be using the generic interface for your comparer:
class MySorter : IComparer<string>
{
public int Compare(string x, string y)
{
}
}
You can then use Linq to sort even objects:
IEnumerable<Person> people = new []
{
new Person
{
Name = "Matthew"
},
new Person
{
Name = "Mark"
}
};
people = people.OrderBy(x => x.Name, new MySorter());
An important note relating to some of the issues you highlighted under Simply Me's answer:
Using the generic interface is always preferable when the types being compared are known, as amongst other things this would have alerted you at compile time rather than run time (when you got an InvalidCastException
) that if you are sorting an array of words, assuming a word is a string
, the IComparer
you are implementing is not fit for purpose as it is comparing two char
types.
(From what I am inferring by looking at your code, I think what you need to do is implement IComparer<string>
and in the Compare
method iterate through each char
of both strings until they differ, and then use your char
comparison logic - but, you should also consider how you handle uppercase and lowercase, what you do when one or both characters are not in your list and if one string
in its entirety matches the first part of the other string
, such as match and matches.)
if (chars.IndexOf((char)x) < chars.IndexOf((char)y))
any idea why? – Mossberg