Split the list into subunits of specified size
This article solves a common problem: how to split a given list into multiple smaller sublists, each containing a predefined number of elements. Existing methods often result in sublist sizes that are larger than expected.
To solve this problem, we recommend using an extension method that is able to split the source list into sublists of a specified size. This method is named ChunkBy
and it leverages LINQ's aggregation and projection capabilities to achieve the desired result.
Please see the following code snippet:
<code class="language-csharp">/// <summary> /// 列表辅助方法。 /// </summary> public static class ListExtensions { public static List<List<T>> ChunkBy<T>(this List<T> source, int chunkSize) { return source .Select((x, i) => new { Index = i, Value = x }) .GroupBy(x => x.Index / chunkSize) .Select(x => x.Select(v => v.Value).ToList()) .ToList(); } }</code>
This method iterates over the elements of the source list and associates each element with its index. It then groups the elements based on the element index divided by the block size. Finally, it projects the group into a sublist containing the element values.
For example, if a list of 18 items is split into sublists of 5 elements each, the result will be a list of 4 sublists distributed as follows: 5-5-5-3.
Note: In .NET 6, LINQ improvements will make splitting easier, as shown in the following example:
<code class="language-csharp">const int PAGE_SIZE = 5; IEnumerable<Movie[]> chunks = movies.Chunk(PAGE_SIZE);</code>
The above is the detailed content of How Can I Efficiently Split a List into Smaller Sublists of a Specific Size?. For more information, please follow other related articles on the PHP Chinese website!