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!