.net - Linq/C#: How to split List into variable length chunks based on list item information? -


i trying split list of type record in linq sub lists based on type information. there 1 record type "a" before , 1 type "b" after each group of records. have class record:

class record {     public string type { get; set; }     public string someotherinformation { get; set; } } 

here sample list (list<record> records):

type    someotherinformation       ...... x       ...... x       ...... b       ......       ...... b       ......       ...... x       ...... x       ...... x       ...... x       ...... x       ...... b       ...... 

the desired output (list<list<record>> lists):

list #1:        list #2:        list #3:       ......        ......        ...... x       ......  b       ......  x       ...... x       ......                  x       ...... b       ......                  x       ......                                 x       ......                                 x       ......                                 b       ...... 

i going through list loop , create new list whenever type "a" , add sub-list list when item's type "b". wondering if there better way to linq. can done linq, if so, how?

i use extension method instead:

public static ienumerable<ienumerable<tsource>> splititems<tsource>(         ienumerable<tsource> source,         func<tsource, bool> startitem,          func<tsource, bool> enditem) {      var templist = new list<tsource>();      int counter = 0;      foreach (var item in source)      {          if (startitem(item) || enditem(item)) counter++;          templist.add(item);          if (counter%2 == 0)          {             yield return templist;             templist = new list<tsource>();          }       }  } 

here usage:

var result = list.splititems(x => x.type == "a", x => x.type == "b").tolist(); 

this return list<ienumerable<record>> 3 items.ofcourse method assumes @ least there 1 start item in beginning , end item @ end.you may want add checks , improve according requirements.


Comments

Popular posts from this blog

apache - Remove .php and add trailing slash in url using htaccess not loading css -

javascript - jQuery show full size image on click -