c# - Small issue with listbox.sort and string compareto-function -
i'm having trouble differences in way listbox sort elements , compareto-function.
the thing is, using 2 listboxes, , trying make 2 lists of elements occurring in 1 of them. both listboxes sorted using sorted property.
my program runs through listboxes, , compare elements 1 one, using compareto-function:
if (listbox1.items[x].tostring().compareto(listbox2.items[y].tostring())) > 0 etc.
now, works fine, except items containing apostrophe (') - in "donald's pizza":
in sorted listbox, "donald's pizza" comes before "donald duck". apostrophe less space. using compareto-function, "donald's pizza" greater "donald duck" . "compareto" says, apostrophe greater space !
this messes system.
if knew apostrophe causes problem, make workaround, i'm not secure if apply other characters too.
as solution i´ll have make own sort-procedure listboxes, overlooking obvious?
edit: answer.
i ended making own sort-procedure, based on compareto-function. way i'm sure sort of listbox 100% equal compareto-function use later.
public listbox fn_sort_listbox(listbox par_listbox) { listbox lb_work = new listbox(); int in_index; int in_compare; if (par_listbox.items.count == 0) return lb_work; foreach (object in par_listbox.items) { in_index = 0; while (in_index < lb_work.items.count) { in_compare = lb_work.items[in_index].tostring().compareto(i.tostring()); if (in_compare > 0) { break; } in_index++; } lb_work.items.insert(in_index, i.tostring()); } return lb_work; }
the example comparer on microsoft's site compares in same order listbox. code below produces "donald's pizza" before "donald duck".
string[] strings = new string[2] { "donald duck", "donald's pizza" }; array.sort(strings, new mystringcomparer(compareinfo.getcompareinfo("en-us"), compareoptions.stringsort)); foreach (string item in strings) console.writeline(item);
the mystringcomparer comes here , implemented as:
public class mystringcomparer : icomparer { private compareinfo mycomp; private compareoptions myoptions = compareoptions.none; // constructs comparer using specified compareoptions. public mystringcomparer(compareinfo cmpi, compareoptions options) { mycomp = cmpi; this.myoptions = options; } // compares strings compareoptions specified in constructor. public int compare(object a, object b) { if (a == b) return 0; if (a == null) return -1; if (b == null) return 1; string sa = string; string sb = b string; if (sa != null && sb != null) return mycomp.compare(sa, sb, myoptions); throw new argumentexception("a , b should strings."); } }
Comments
Post a Comment