Hi Ali,
Use Array.Sort with a custom class or struct of your choice that implements the kind of sorting you need.
The code sample below tells Array.Sort to use the sorting implemented in SortClass. SortClass is designed purely for sorting. All it does is stripping away the number in front and uses the standard numeric comparison on that number. Reverse the result of the sorting or change the sort procedure to do it for you.
protected override void OnLoad(EventArgs e)
{
string[] strings = {"2.3%<A other text here>",
"-4%<B other text here>",
"10%<C other text here>",
"-9.3%<D other text here>",
"22%<E other text here>"};
Array.Sort(strings, new SortClass());
Array.Reverse(strings);
listBox1.Items.AddRange(strings);
}
public class SortClass : IComparer
{
public int Compare(object x, object y)
{
if(!(x is String) || !(y is String))
throw new InvalidCastException("object is not of type string");
string a = (string)x;
string b = (string)y;
int i = a.IndexOf('%');
int j = b.IndexOf('%');
if(i < 1 || j < 1)
throw new FormatException("string is not of expected format");
a = a.Substring(0, i);
b = b.Substring(0, j);
double d = 0;
double e = 0;
if(!double.TryParse(a, NumberStyles.Float, CultureInfo.InvariantCulture, out d)
|| !double.TryParse(b, NumberStyles.Float, CultureInfo.InvariantCulture, out e))
throw new FormatException("string is not of expected format");
return d.CompareTo(e);
}
}
--
Happy coding!
Morten Wennevik [C# MVP]