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

How Can I Efficiently Split a Collection into Subsets Using LINQ?

Mary-Kate Olsen
Mary-Kate OlsenOriginal
2025-01-20 03:51:09957browse

How Can I Efficiently Split a Collection into Subsets Using LINQ?

LINQ: A Powerful Tool for Subset Creation

Data manipulation often requires dividing large collections into smaller, manageable subsets. LINQ (Language Integrated Query) provides an elegant and efficient solution for this common task.

The LINQ Solution

The following LINQ extension method effectively splits a collection into multiple subsets:

<code class="language-csharp">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 method accepts a collection (list) and the desired number of subsets (parts). It leverages LINQ's GroupBy and Select operators to partition the input. The modulo operator (%) ensures even distribution across the subsets, handling cases where the collection size isn't perfectly divisible by parts.

Practical Application

Here's how to use the Split method:

<code class="language-csharp">List<int> numbers = Enumerable.Range(1, 100).ToList();
IEnumerable<IEnumerable<int>> splitNumbers = numbers.Split(5);</code>

This example divides a list of 100 integers into 5 subsets. Note that the resulting subsets might have varying sizes if the original collection's size isn't a multiple of parts.

Benefits of the LINQ Approach

Employing LINQ for this task offers several key advantages:

  • Readability: The concise LINQ syntax enhances code clarity.
  • Performance: LINQ's optimized implementation ensures efficient processing.
  • Versatility: The method is adaptable to various collection types and subset sizes.

The above is the detailed content of How Can I Efficiently Split a Collection into Subsets 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