Listbox numerical sort

  • Thread starter Thread starter Ali Chambers
  • Start date Start date
A

Ali Chambers

Hi,

I have a bit of a problem with a sort procedure I need to do. I have a
list of items in a listbox, eg:-

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>

How do I sort these listbox items in numerical descending order to:

22%<E other text here>
10%<C other text here>
2.3%<A other text here>
-4%<B other text here>
-9.3%<D other text here>

Thanks,
Alex
 
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);
}
}
 
Hi Morten,

Thanks! I'm a VB.NET coder (and a new one as well) - can this code be
translated to VB?

Alex
 
Not sure about VB, but the VB.Net code should be almost identical other that syntactical differences. Don't know enough VB.Net to try to write code though.
 
Back
Top