Getting Every Nth Item from a List
Obtaining every nth item from a list is a common operation in programming. Whether you're working with .NET 3.5 or a more recent version, there are various approaches to achieve this functionality.
Lambda Expression Approach
Lambda expressions provide a concise way to filter data in .NET. In this case, you can use a lambda expression to check whether the index of each item is divisible by the desired increment (n). The following code snippet demonstrates this approach:
using System.Collections.Generic; class Program { static void Main() { // Create a List<int> with some sample data List<int> list = new List<int> { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 }; // Obtain every 3rd item int n = 3; var everyNthItem = list.Where((x, i) => i % n == 0); // Print the resulting list Console.WriteLine(string.Join(",", everyNthItem)); } }
LINQ Approach
Alternatively, you can use the LINQ (Language Integrated Query) syntax to achieve the same result. LINQ provides a more domain-specific language for querying data in .NET. The following code snippet shows how to use LINQ in this context:
using System.Linq; class Program { static void Main() { // Create a List<int> with some sample data List<int> list = new List<int> { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 }; // Obtain every 3rd item int n = 3; var everyNthItem = list.Where((x, i) => i % n == 0); // Print the resulting list Console.WriteLine(string.Join(",", everyNthItem)); } }
The above is the detailed content of How to Get Every Nth Item from a List in C#?. For more information, please follow other related articles on the PHP Chinese website!