Home > Backend Development > C++ > How Can I Efficiently Split a List into Smaller Sublists of a Specific Size?

How Can I Efficiently Split a List into Smaller Sublists of a Specific Size?

Linda Hamilton
Release: 2025-01-18 04:36:10
Original
518 people have browsed it

How Can I Efficiently Split a List into Smaller Sublists of a Specific Size?

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>
Copy after login

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>
Copy after login

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!

source:php.cn
Statement of this Website
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
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template