Split a collection into parts using LINQ
This article explores a common problem in data analysis and programming: splitting a set into n different subsets.
LINQ solution:
LINQ provides a simple and elegant solution for this task. The following extension method Split<T>
achieves the expected result:
<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>
Instructions:
Split<T>
method accepts two parameters: the input collection (list
) and the number of parts to split it into (parts
). i
to zero, which will be used as the index of the grouped element. group by
syntax to create groups based on the modulo of i
and parts
. This ensures that elements are assigned to different parts based on their position in the original collection. IEnumerable<T>
objects, each object representing a part of the original collection. This solution provides a convenient and readable way to split a collection into subsets using LINQ.
The above is the detailed content of How Can I Split a Collection into Multiple Parts Using LINQ?. For more information, please follow other related articles on the PHP Chinese website!