This post will discuss how to split a list into sublists of size n in C#.

1. Using Enumerable.GroupBy() method

In LINQ, you can use the Enumerable.GroupBy() method to partition a list into multiple sublists. It groups the elements of a sequence according to a specified key selector function. The following code example demonstrates how the combination of Select() and GroupBy() method can break a list into the sublists according to the specified chunk size:

Download  Run Code

Output:

1, 2
3, 4
5

2. Using List<T>.GetRange() method

The List<T>.GetRange() method is used to get elements between the desired range from a List<T>. The following example demonstrates the usage of the List<T>.GetRange() method for splitting a List<T> into specified number of chunks of equal sizes.

Download  Run Code

Output:

1, 2
3, 4
5

 
The above generic extension method returns an IEnumerable. To return a List instead, do as follows:

Download  Run Code

Output:

1, 2
3, 4
5

3. Using Enumerable.Take() method

Alternatively, you can use the Enumerable.Take() method to split a list of items into chunks of a specific size. The Take() method returns a specified number of contiguous elements from the start of a sequence, and can be used as follows:

Download  Run Code

Output:

1, 2
3, 4
5

That’s all about splitting a list into sublists of size n in C#.