Home > Backend Development > C++ > How Can I Split a Collection into Multiple Parts Using LINQ?

How Can I Split a Collection into Multiple Parts Using LINQ?

DDD
Release: 2025-01-20 03:41:09
Original
647 people have browsed it

How Can I Split a Collection into Multiple Parts Using LINQ?

Split a collection into parts using LINQ

This article explores a common problem in data analysis and programming: splitting a set into n different subsets.

LINQ solution:

LINQ provides a simple and elegant solution for this task. The following extension method Split<T> achieves the expected result:

<code class="language-csharp">static class LinqExtensions
{
    public static IEnumerable<IEnumerable<T>> Split<T>(this IEnumerable<T> list, int parts)
    {
        int i = 0;
        var splits = from item in list
                     group item by i++ % parts into part
                     select part.AsEnumerable();
        return splits;
    }
}</code>
Copy after login

Instructions:

    The
  • Split<T> method accepts two parameters: the input collection (list) and the number of parts to split it into (parts).
  • It initializes the counter i to zero, which will be used as the index of the grouped element.
  • This method uses the group by syntax to create groups based on the modulo of i and parts. This ensures that elements are assigned to different parts based on their position in the original collection.
  • Finally, the result is projected to produce a collection of IEnumerable<T> objects, each object representing a part of the original collection.

This solution provides a convenient and readable way to split a collection into subsets using LINQ.

The above is the detailed content of How Can I Split a Collection into Multiple Parts Using LINQ?. 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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template