This post will discuss how to conditionally split a list in C#.

We can use the Enumerable.GroupBy() method to conditionally group the elements based on some condition. For example, the following code split a list into sublists based on odd-even values:

Download  Run Code

Output:

1, 3, 5
2, 4

 
The GroupBy() method can also be used to conditionally split the list based on a certain property. The following code example shows how to split a list of students into sublists based on their age:

Download  Run Code

Output:

[Olivia, 10], [John, 15]
[Robert, 20]

That’s all about conditionally splitting a list in C#.