c# - Sorting a custom object list -


i have list<> containing object class has string property want sort using following rule:

  1. all objects inside list "code" x5 should on top of list.
  2. all objects inside list "code" g2 after x5 objects.
  3. all objects inside list "code" h3 after g2 objects.
  4. 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:

  1. sam
  2. jennifer
  3. jack
  4. 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

Popular posts from this blog

user interface - How to replace the Python logo in a Tkinter-based Python GUI app? -

objective c - Greedy NSProgressIndicator Allocation -

how to set an OCR language in Google Drive -