Get a slice or a sublist of a List in C#
This post will discuss how to get a slice or a sublist of a list in C#.
1. Using GetRange() Method
The recommended solution to get a copy of the source list between the specified range is using the List<T>.GetRange() method. The following example demonstrates how you can use the GetRange() method to get a sublist of a list.
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 |
using System; using System.Collections.Generic; public class Example { public static void Main() { List<int> values = new List<int>() { 1, 2, 3, 4, 5 }; int start = 1; int end = 3; List<int> subList = values.GetRange(start, end); Console.WriteLine(String.Join(", ", subList)); // 2, 3, 4 } } |
If you need to delete the range of items from the source list, use the List<T>.RemoveAt(Int32) method that takes the index of the List<T> and remove the element at that index.
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 |
using System; using System.Collections.Generic; public class Example { public static void Main() { List<int> values = new List<int>() { 1, 2, 3, 4, 5 }; int start = 1; int end = 3; for (int index = end; index >= start; index--) { values.RemoveAt(index); } Console.WriteLine(String.Join(", ", values)); // 1, 5 } } |
2. Using Where() Method
With LINQ, you can use the Where() method to filters a sequence of values based on a predicate. The following code example demonstrates how you can use the Where() method to get a slice of a list in C#.
|
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> values = new List<int>() { 1, 2, 3, 4, 5 }; int start = 1; int end = 3; List<int> subList = values.Where((value, index) => index >= start && index <= end) .ToList(); Console.WriteLine(String.Join(", ", subList)); // 2, 3, 4 } } |
That’s all about getting a slice or a sublist of 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 :)