Order List of Objects by List inside object c# -


i have list of objects (obj1) , inside each object have list of objects shown below:

list <obj1> obj1

obj1

  • string name
  • list <obj2> obj2

obj2

  • string name
  • int id

i want order list of obj1 order marked list of obj2 ids.

first element in list of obj2 defines order of obj1 list, if same second 1 defines order, , on until end of list of obj2.

example data:

  • "test" : {("a", 2), ("b", 3)}
  • "test2" : {(("c", 1), ("d", 2)}
  • "test3" : {(("a", 2), ("b", 2), ("c", 3)}

result data:

  • "test2" : {(("c", 1), ("d", 2)}
  • "test3" : {(("a", 2), ("b", 2), ("c",3)}
  • "test" : {("a", 2), ("b", 3)}

the following solution implement icomparable interface int compareto(object obj) method obj2 , obj1.
obj2 has compared it's id , obj1 compared list<obj2>.
can call sort() on list like: list<obj1>.

here on ideone full working live example complete code.

the following code snippets needed , described above:

class obj2 : icomparable {     public string name { get; set; }     public int id { get; set; }      // ...      public int compareto(object obj)     {         obj2 other = obj obj2;         return id.compareto(other.id);     } }  class obj1 : icomparable {     public string name { get; set; }     public list<obj2> objects { get; set; }      // ...      public int compareto(object obj)     {         obj1 other = obj obj1;         /* loop until 1 list ends */         (int idx = 0; idx < objects.count && idx < other.objects.count; ++idx)         {             int comparison = objects[idx].id.compareto(other.objects[idx].id);             /* if not equal return */             if (comparison != 0)             {                 return comparison;             }         }         /* if equal until use count compare */         return objects.count - other.objects.count;     } } 

resulting output:

"test2" : { ("c", 1) ("d", 2) } "test3" : { ("a", 2) ("b", 2) ("c", 3) } "test" : { ("a", 2) ("b", 3) } 

Comments

Popular posts from this blog

Is there a better way to structure post methods in Class Based Views -

performance - Why is XCHG reg, reg a 3 micro-op instruction on modern Intel architectures? -

jquery - Responsive Navbar with Sub Navbar -