I have a collection of strings in c#, for example;
var example = new string[]{"c", "b", "a", "d"};
I then with to sort this, but my IComparer method is not working, and looping infinitely by the seems of things.
Basically I need "b"
to come first, followed by "c"
, then I dont care about the order of any of the others.
Is this possible using IComparer<string>
and the Compare(string x, string y)
method?
Edit: Code
public int Compare(string x, string y)
{
var sOrder = new string[] { "b", "c" };
int index_x = -1;
int index_y = -1;
for (int i = 0; i < sOrder.Length;i++)
{
if (sOrder[i] == x)
index_x = i;
else if (sOrder[i] == y)
index_y = i;
}
if (index_x >= 0 && index_y >= 0)
{
if (index_x < index_y)
{
return -1;
}
else
return 1;
}
return 0;
}
This should do what you want:
A simple way is to substitute integers for the strings.
Note that this isn't a stable sort. If you need a stable sort, there's a little more work involved.