Reputation: 93
I have several columns in a listview but I am just so dummb to think up a logical sorting method to both sort items out alphabetically and numerically. Because in case of numerical values I'd like a column's content such as:
111 13 442 23 214
to be:
13 23 111 214 442
My current sorting class looks like this:
class itemsorter:IComparer
{
public int compare (object a, object b)
{
return string.compare(((lvitem)a).text,((lvitem)b).text));
}
}
Upvotes: 0
Views: 635
Reputation: 1553
As ziesemer said, you can take my sample code as below, hope this will give you a hand.
class itemsorter : IComparer
{
public int compare(object a, object b)
{
int resultA, resultB;
bool markA = int.TryParse(((lvitem)a).text, out resultA);
bool markB = int.TryParse(((lvitem)b).text, out resultB)
// They are number.
if (markA && markB)
{
if (resultA > resultB)
return 1;
else if (resultA < resultB)
return -1;
else
return 0;
}
// a can convert to number,
// b can't.
if (markA && !markB)
{
return 1;
}
// b can convert to number,
// a can't.
if(!markA && markB)
{
return -1;
}
}
}
Upvotes: 0
Reputation: 28687
Parse your Strings to numbers before doing the comparison, in which case you can simply return the difference of the 2 numbers as your result from the compare
method.
As it sounds like you still want to sort both alphabetical and numerical values, this would have to be a combined, hybrid approach with the above - such that numbers are sorted against numbers, and alphabetical values with alphabetical. You'd just need to choose which takes precedence, such that either numerical or alphabetical values always come first - necessary to maintain a stable and reflexive sort. (For example, if a
is a number, and b
is a non-number, return 1. If a
is a non-number, and b
is a number, return -1. Else, they must be of equal types, and then you can defer to the type-specific sorting.)
Upvotes: 1