c# - Merge two or more T in List<T> based on condition -


i have below class:

public class factoryorder     {         public string text { get; set; }         public int orderno { get; set; }             } 

and collection holding list of factoryorders

list<factoryorder>() 

here sample data

factoryorder("apple",20) factoryorder("orange",21) factoryorder("watermelon",42) factoryorder("jackfruit",51) factoryorder("grapes",71) factoryorder("mango",72) factoryorder("cherry",73) 

my requirement merge text of factoryorders orderno in sequence , retain lower orderno merged factoryorder - resulting output

   factoryorder("apple orange",20) //merged apple , orange , retained lower orderno 20     factoryorder("watermelon",42)     factoryorder("jackfruit",51)     factoryorder("grapes mango cherry",71)//merged grapes,mango,cherry , retained lower orderno 71 

i new linq not sure how go this. or pointers appreciated

as commented, if logic depends on consecutive items heavily linq not easiest appoach. use simple loop.

you order them first linq: orders.orderby(x => x.orderno )

var consecutiveordernogroups = new list<list<factoryorder>> { new list<factoryorder>() }; factoryorder lastorder = null; foreach (factoryorder order in orders.orderby(o => o.orderno)) {     if (lastorder == null || lastorder.orderno == order.orderno - 1)         consecutiveordernogroups.last().add(order);     else         consecutiveordernogroups.add(new list<factoryorder> { order });      lastorder = order; } 

now need build list of factoryorder joined names every group. linq , string.join can come in handy:

orders = consecutiveordernogroups     .select(list => new factoryorder      {          text    = string.join(" ", list.select(o => o.text)),         orderno = list.first().orderno // minimum number     })     .tolist(); 

result sample:

http://fs1.directupload.net/images/150619/9bmfc7xk.jpg


Comments

Popular posts from this blog

twig - Using Twigbridge in a Laravel 5.1 Package -

firemonkey - How do I make a beep sound in Android using Delphi and the API? -

jdbc - Not able to establish database connection in eclipse -