c# - Sorting a list<object> using an array -


i can't seem head around this.
have following:

private string[] prefered = new string[] { "37", "22", "18" };      private list<stream> library;      public class stream     {         public string id { get; set; }         public string url { get; set; }         public string description { get; set; }         public string type { get; set; }     } 

and sort list<stream> named library using prefered string array result library following order: 35,22,18,...

library = library.orderby(o => array.indexof(prefered, o.id)).tolist(); 

but i'm not getting expected result...

json

[{"id":"44","url":null,"description":".webm (854x480)","type":".webm"}, {"id":"35","url":null,"description":".3gp (854x480)","type":".3gp"}, {"id":"43","url":null,"description":".webm (640x360)","type":".webm"}, {"id":"34","url":null,"description":".flv (640x360)","type":".flv"}, {"id":"18","url":null,"description":".mp4 (480x360)","type":".mp4"}, {"id":"5","url":null,"description":".flv (400x240)","type":".flv"}, {"id":"36","url":null,"description":".flv (400x240)","type":".flv"}, {"id":"17","url":null,"description":".3gp (176x144)","type":".3gp"}]  

i think works cases prefered doesn't contain ids in library.

var ranks =     prefered         .select((x, n) => new { x, n })         .tolookup(xn => xn.x, xn => xn.n);  library =     library         .orderby(l =>             ranks[l.id]                 .defaultifempty(int.maxvalue)                 .first())         .tolist(); 

here explanation, per request int comments.

the line .select((x, n) => new { x, n }) projects sequence of values sequence of values , index in sequence.

the line .tolookup(xn => xn.x, xn => xn.n) changes sequence dictionary-like structure returns list of 0 or more values key provided, regardless if key in original sequence or not. if key not in original sequence empty sequence of values in return.

the expression ranks[l.id] takes each id in library sequence , applies lookup, return sequence of values. expression .defaultifempty(int.maxvalue) ensures sequence has @ least 1 value, , expression .first() returns first value of sequence. ensures ever id in library source possible matching index value prefered sequence, or int.maxvalue if id not in prefered sequence.

then simple matter of ordering returned value , recreating list .tolist().


Comments

Popular posts from this blog

java.util.scanner - How to read and add only numbers to array from a text file -

rewrite - Trouble with Wordpress multiple custom querystrings -