Home > Backend Development > C++ > How Can I Split a Collection into Subsets of (Nearly) Equal Size Using LINQ?

How Can I Split a Collection into Subsets of (Nearly) Equal Size Using LINQ?

Linda Hamilton
Release: 2025-01-20 03:46:09
Original
591 people have browsed it

How Can I Split a Collection into Subsets of (Nearly) Equal Size Using LINQ?

Split a collection into subsets using LINQ

LINQ allows dividing a collection into a specified number of subsets. Unlike even splitting, the last subset may have a different number of elements than the other subsets.

To achieve this we can use a simple LINQ extension method:

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

Using this method, you can divide the collection into sub-collections while ensuring that the last subset may be of different sizes. The above code does this by grouping elements based on their index modulo the number of subsets, effectively assigning them to different subsets.

The above is the detailed content of How Can I Split a Collection into Subsets of (Nearly) Equal Size Using LINQ?. For more information, please follow other related articles on the PHP Chinese website!

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