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