Home >Backend Development >C++ >How Can LINQ Be Used to Split a Collection into Proportionate Parts?

How Can LINQ Be Used to Split a Collection into Proportionate Parts?

Patricia Arquette
Patricia ArquetteOriginal
2025-01-20 03:56:07294browse

How Can LINQ Be Used to Split a Collection into Proportionate Parts?

Efficiently Dividing Collections with LINQ

Data manipulation often requires splitting large collections into smaller, manageable subsets. LINQ provides an elegant solution for this common task. The following LINQ extension method effectively divides a collection into a specified number of proportionate parts:

<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>

This extension method leverages LINQ's grouping functionality. It uses the modulo operator (%) to distribute elements evenly across the desired number of parts. The output is an IEnumerable of IEnumerable<T>, where each inner IEnumerable<T> represents a portion of the original collection.

The above is the detailed content of How Can LINQ Be Used to Split a Collection into Proportionate Parts?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
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