Reputation: 954
I want to change the sorting of strings so it is based off the following alphabet:
A,E,I,O,U,F,G,L,M,N,P,S,T,V,H,K,R
Instead of the standard A,B,C,D ... X,Y,Z
So I started to try and create a IComparer but stuck on how to implement.
Here is what I got so far which ain't much.
public class CustomSort : IComparer<string>
{
public int Compare(string a, string b)
{
return 1;
}
}
Any help would be much appreciated.
Upvotes: 0
Views: 2021
Reputation: 111940
It should be something very like this:
In the end you compare character by character, finding the "index" of the character inside a Order
string. Perhaps to speed it up you could convert the Order
string to a Dictionary<char, int>
where the int
is the "weight".
public class CustomSort : IComparer<string>
{
public const string Order = "AEIOUFGLMNPSTVHKR";
public int Compare(string a, string b)
{
if (a == null)
{
return b == null ? 0 : -1;
}
if (b == null)
{
return 1;
}
int minLength = Math.Min(a.Length, b.Length);
for (int i = 0; i < minLength; i++)
{
int i1 = Order.IndexOf(a[i]);
int i2 = Order.IndexOf(b[i]);
if (i1 == -1)
{
throw new Exception(a);
}
if (i2 == -1)
{
throw new Exception(b);
}
int cmp = i1.CompareTo(i2);
if (cmp != 0)
{
return cmp;
}
}
return a.Length.CompareTo(b.Length);
}
}
Upvotes: 3