Home >Backend Development >C++ >How Can I Split a Collection into Sub-Collections Using LINQ?

How Can I Split a Collection into Sub-Collections Using LINQ?

Linda Hamilton
Linda HamiltonOriginal
2025-01-20 04:01:09838browse

How Can I Split a Collection into Sub-Collections Using LINQ?

Use LINQ to divide the collection into sub-collections

Splitting a collection into smaller parts is a common programming task. Using LINQ (Language Integrated Query) you can achieve this with a simple extension method.

Divide the set into N parts

The

extension method Split receives as input a collection and the desired number of parts and returns a IEnumerable<IEnumerable> representing the subcollection. This algorithm divides elements into parts based on the remainder when the current index is divided by the number of parts.

Implementation:

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

Usage:

The

Split method can be used on any IEnumerable collection. For example, to split a list of numbers into 3 parts:

<code class="language-csharp">var numbers = new List<int> { 1, 2, 3, 4, 5, 6, 7, 8, 9 };
var parts = numbers.Split(3);</code>

This will return a IEnumerable containing 3 IEnumerable collections, each containing a subset of the original list:

<code>部分1:{ 1, 4, 7 }
部分2:{ 2, 5, 8 }
部分3:{ 3, 6, 9 }</code>

The above is the detailed content of How Can I Split a Collection into Sub-Collections Using LINQ?. 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