c# - Sorting a custom object list -
i have list<> containing object class has string property want sort using following rule:
- all objects inside list "code"
x5should on top of list. - all objects inside list "code"
g2afterx5objects. - all objects inside list "code"
h3afterg2objects. - all other object should @ end of list, sorted alphabetically "code".
i tried code kept throwing exception:
system.argumentexception: unable sort because icomparer.compare() method returns inconsistent results. either value not compare equal itself, or 1 value repeatedly compared value yields different results. icomparer: ''.
code attempt:
public class myobject: icomparable<myobject> { int id { get; set; } string name { get; set; } string code { get; set; } public myobject() { } public int compareto(myobject other) { //i don't know how write sort logic } } later create list of "myobject" , sort it:
list<myobject> objects = new list<myobject>(); objects.add(new myobject() { id = 0, name = "jennifer"; code = "g2"; }); objects.add(new myobject() { id = 1, name = "tom"; code = "h3"; }); objects.add(new myobject() { id = 2, name = "jack"; code = "g2"; }); objects.add(new myobject() { id = 3, name = "sam"; code = "x5"; }); objects.sort(); and list in following order:
- sam
- jennifer
- jack
- tom
if necessary implement icomparable can use above answer. can in-place.
objects.orderby( o => o.code == "x5" ? 1 : o.code == "g2" ? 2 : o.code == "h3" ? 3 : 4); if want ordering in group (i.e. g2) can add thenby well.
Comments
Post a Comment