Instead of trying to override the CompareTo
method on the string
class (which you can't do anyway because the string
class is sealed), create an IComparer<string>
class and pass an instance of that to Arrays.Sort()
.
public class StringLengthComparer : IComparer<string>
{
public int Compare(string x, string y)
{
if (x.Length > y.Length)
return 1;
if (x.Length < y.Length)
return -1;
return 0;
}
}
public class Program
{
static void Main(string[] args)
{
string[] arrayStrings =
new string[] { "a", "b", "the", "roof", "is", "on", "fire" };
Array.Sort(arrayStrings, new StringLengthComparer());
foreach (var item in arrayStrings)
{
Console.WriteLine(item);
}
}
}
Output:
a
b
is
on
the
roof
fire