c# - Use OrderBy in a LINQ predicate? -


in code need sort collection either price or rating.totalgrade , can see both linq querys same statement minor difference.

i thinking using linq predicate instead can see the orderby main difference , found no sample using orderby in query. possible or there other ways shorten code, maybe there more conditions in future.

if (currentdisplaymode == crschartrankinggraphdisplaymode.position) {     this.collectioncompletesorted = new list<result>(from co in collection                                     co.isvirtual == false                                     orderby co.price, co.currentranking                                     select co); } else if (currentdisplaymode == crschartrankinggraphdisplaymode.grade) {     this.collectioncompletesorted = new list<result>(from co in collection                                     co.isvirtual == false                                     orderby co.rating.totalgrade, co.currentranking                                     select co); } 

you can make use of deffered nature of linq , ability compose queries.

probably using code this:

        var basequery = co in collection !co.isvirtual select co; // base of query         iorderedenumerable<result> orderedquery; // result of first ordering, must of type, able call thenby          switch(currentdisplaymode) // use enum here         { // primary ordering based on enum             case crschartrankinggraphdisplaymode.position: orderedquery = basequery.orderby(co => co.price);                 break;             case crschartrankinggraphdisplaymode.grade: orderedquery = basequery.orderby(co => co.totalgrade);                 break;         }          this.collectioncompletesorted = orderedquery.thenby(co => co.currentranking).tolist(); // secondary ordering , conversion list 

its easy understand , avoids converting list until end.


Comments

Popular posts from this blog

php - What is the difference between $_SERVER['PATH_INFO'] and $_SERVER['ORIG_PATH_INFO']? -

fortran - Function return type mismatch -

queue - mq_receive: message too long -