Edgars Miškins Edgars Miškins - 1 month ago 17
Vb.net Question

Sort a list of custom objects by object property numerical values in vb.net

I want to sort a list of custom objects by object property numerical values.

For example, I have custom object

MyObject
with properties:

MyObject.A
MyObject.B
MyObject.C


Where
A
is a string containing number values,
B
and
C
are Strings containing text.

I want to sort the list containing these objects by the
A
property from smallest number to largest.

I tried using this:

MyList = MyList.OrderBy(Function(i) i.A).ToList()


But this sorts the list as if the numbers were strings.
For example, I get the result:
1,10,11,2,3,4
.
What I actually wanted was this:
1,2,3,4,10,11


How can I sort the list by numerical values?

Answer

Then this is not a double-property but a string which displays doubles. Either always convert this string to double which isn't very efficient, or store them as double and only convert them to strings where you need to display them (recommended).

However, here is the Parse approach:

MyList = MyList.OrderBy(Function(i) Double.Parse(i.A)).ToList()

If it contains dots and you use commas(as commented) use:

MyList = MyList.OrderBy(Function(i) Double.Parse(i.A, CultureInfo.InvariantCulture)).ToList()