Home > Backend Development > C++ > How to Get Every Nth Item from a List in C#?

How to Get Every Nth Item from a List in C#?

Mary-Kate Olsen
Release: 2024-12-29 16:56:10
Original
284 people have browsed it

How to Get Every Nth Item from a List in C#?

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));
    }
}
Copy after login

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));
    }
}
Copy after login

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!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template