c# - Efficient List Ordering -
i testing whats best algorithm order list key value.
i have simple object (following code snippets c#)
class basicobject { int key; }
the key gets randomly set when constructing object.
so have list of basicobject
objects needs ordered key value in end.
list<basicobject> basiclist = new list<basicobject>(); (int = 0; < someamount; i++) { basiclist.add(new basicobject()); }
my idea was, make new list called orderedlist
or so, , loop through every time, every basicobject
, , check whether key higher current value or lower. that:
list<basicobject> orderedlist = new list<basicobject>(); bool objectwasinserted = false; orderedlist.add(basiclist[0]); // inserting 1 object reference upcoming loop (int = 1; < someamount; i++) { objectwasinserted = false; (int c = 0; c < orderedlist.count; c++) { if (basiclist[i].key > orderedlist[c].key) // key of current object higher key of current object of ordered list { orderedlist.insert(c, basiclist[i]); objectwasinserted = true; break; } } if (!objectwasinserted) { orderedlist.add(basiclist[i]); } }
even though works, way slow. tested 50000 objects takes 8 seconds.
the linq method orderby
faster.
orderedlist = basiclist.orderbydescending(x => x.key).tolist();
takes 7 milli seconds 50000 objects!
however, helper method, want away , rather use own algorithm order list of objects key.
i tried linkedlist instead of normal list. little bit faster, still far away linq method.
so there way, speed ordering of objects little? :)
thanks help, in advance!!
if don't want use linq (which looks strange me), can use list<t>.sort
:
basiclist.sort((o1,o2) => o1.key.compareto(o2.key));
note: method modify original list instead of creating new one.
Comments
Post a Comment