Brian Dahl

Brian Dahl

  • NA
  • 9
  • 19.6k

Split a list into sub-lists taking

Jul 6 2018 3:00 AM
Hi i have the following Problem. I have a list and i want to divide the List into sub-lists dependend from a value from a cell.
For Example:
I have a List<DataRow> and in the column "Name" from every DataRow start the Sublist  with the value "Start" and end it with "End".
I have solved it with the following code, but i want to know if there is a more efficent way to solve it? 
  1. var rowsFromTable = table.AsEnumerable().ToList();  
  2.     List<List<DataRow>> chunks = new List<List<DataRow>>();  
  3.     IEnumerable<DataRow> rest;  
  4.     do   
  5.     {  
  6.         rest = rowsFromTable.Except(chunks.SelectMany(c => c));  
  7.           
  8.         var extractRows = rest.TakeWhile((row, index) => (string)row["Name"] != "Start" || index == 0).ToList();  
  9.           
  10.         chunks.Add(extractRows);  
  11.     }  
  12.     while(rest.Any());  
 Best Regards
Brian Dahl 

Answers (1)