Conditionally Split a List in C#
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:
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 |
using System; using System.Linq; using System.Collections.Generic; public class Example { public static void Main() { List<int> nums = new List<int>() { 1, 2, 3, 4, 5 }; // split list into odd-even var partitions = nums.GroupBy(x => x % 2 == 0); foreach (var partition in partitions) { Console.WriteLine(String.Join(", ", partition)); } } } |
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:
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 |
using System; using System.Linq; using System.Collections.Generic; class Student { public string name { get; set; } public decimal age { get; set; } public override string ToString() { return "[" + name + ", " + age + "]"; } } public class Example { public static void Main() { List<Student> values = new List<Student> { new Student{name = "Olivia", age = 10}, new Student{name = "Robert", age = 20}, new Student{name = "John", age = 15} }; // split list based on age var partitions = values.GroupBy(x => x.age >= 18); foreach (var partition in partitions) { Console.WriteLine(String.Join(", ", partition)); } } } |
Output:
[Olivia, 10], [John, 15]
[Robert, 20]
That’s all about conditionally splitting a list in C#.
Thanks for reading.
To share your code in the comments, please use our online compiler that supports C, C++, Java, Python, JavaScript, C#, PHP, and many more popular programming languages.
Like us? Refer us to your friends and support our growth. Happy coding :)