Iterate from second element of a List in C#
This post will discuss how to iterate from the second element of a List in C#.
The foreach statement provides a simple, clean way to iterate through the elements of a sequence. The idea is to use the Enumerable.Skip method to skip the first element in a list.
The following example demonstrates the usage of a foreach statement to iterate from the second element of a list. The code can be easily modified to skip the desired number of items from the beginning of a sequence.
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 |
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 }; foreach (var i in nums.Skip(1)) { Console.WriteLine(i); } } } |
Output:
2
3
4
5
To print the specified number of items from the start of a sequence, consider using the Enumerable.Take method.
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 |
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 }; foreach (var i in nums.Take(3)) { Console.WriteLine(i); } } } |
Output:
1
2
3
Alternatively, you can use the traditional for-loop to iterate over a list starting from the second index. Here’s what the code would look like:
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 |
using System; using System.Collections.Generic; public class Example { public static void Main() { List<int> nums = new List<int>() { 1, 2, 3, 4, 5 }; for (var i = 1; i < nums.Count; i++) { Console.WriteLine(nums[i]); } } } |
Output:
2
3
4
5
That’s all about iterating from the second element 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 :)