Skip to main content

Posts

Showing posts from May, 2016

Split list into sublists using LINQ in C#.NET

Here is the sample LINQ C# code to split list into sublists public   static   List < List <T>> Split < T >(   this   List   <T>  source ,  int   NumberOfGroup   )         {              return   source                 . Select (( x   ,  i )=> new   {  Index   =  i ,  Value   =  x   })                 . GroupBy ( x   =>  x . Index   /  NumberOfGroup   )                 . Select ( x   =>  x . Select   ( v   =>  v . Value ). ToList ())                 . ToList ();         } The idea is to first group the elements by indexes. Dividing by  NumberOfGroup  as the effect of grouping them into groups of NumberOfGroup. Then convert each group to a list and the IEnumerable of List to a List of Lists For reference try this link - http://stackoverflow.com/questions/419019/split-list-into-sublists-with-linq Similar to list we can divide dictionary also in sub-dictionaries. Here is the sample code public   static   List <   Dictio