need help with Compare() function

W

Wee Bubba

i have completed a Compare() function to help me sort the contents of
a ListBox. I wanted to give the user of the class the ability to sort
by EITHER ListItem.Text OR ListItem.Value. ALSO sometimes the text
items/values will be integers and sometimes plain text.

to get around this i implemented 2 public properties on my class. 1
property allows the user to select whether they want to sort by
ListItem.Text or By ListItem.Value property. The other property
allows them to select whether the content type is String or Integer.
i am then looking at these properties and using if/else statements.
but i know that my logic here is messy and prone to error (i am a
beginner) so can anyone suggest a better way for me to achieve this?
thanks. heres my function:


public int Compare(object x, object y)

{

if (dm.contentType == ContentType.String)

{

string sx = "";

string sy = "";

if (dm.sortMode == SortMode.Text)

{

sx = ((ListItem) x).Text;

sy = ((ListItem) y).Text;

}

else

{

sx = ((ListItem) x).Value;

sy = ((ListItem) y).Value;

}

return sx.CompareTo(sy) * this.direction;

}

else

{

int sx = 0;

int sy = 0;

if (dm.sortMode == SortMode.Text)

{

sx = int.Parse(((ListItem) x).Text);

sy = int.Parse(((ListItem) y).Text);

}

else

{

sx = int.Parse(((ListItem) x).Value);

sy = int.Parse(((ListItem) y).Value);

}

return sx.CompareTo(sy) * this.direction;

}

}
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,744
Messages
2,569,479
Members
44,899
Latest member
RodneyMcAu

Latest Threads

Top