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 ListsFor 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< Dictionary<T1, T2>>Split< T1, T2 >(this Dictionary<T1, T2> 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 ).ToDictionary( z => z.Key , z => z.Value ))
.ToList();
}
Other useful LINQ operations:
Remove element from array :
int[] numbers = { 1, 3, 4, 9, 2 }; int numToRemove = 4; numbers = numbers.Where(val => val != numToRemove).ToArray();
Comments
Post a Comment