Home >Backend Development >C++ >How to Efficiently Split a List into Smaller Sublists of a Defined Size?

How to Efficiently Split a List into Smaller Sublists of a Defined Size?

DDD
DDDOriginal
2025-01-18 04:26:08483browse

How to Efficiently Split a List into Smaller Sublists of a Defined Size?

Split the list into sublists of specified size

This article introduces how to split a list into sublists of specified size and provides two efficient methods.

Method 1: Use extension methods

The following code shows how to implement list splitting through extension methods:

<code class="language-csharp">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>

Usage: Directly call the ChunkBy method of the list, passing in the required block size as a parameter. For example, split a list of 18 elements into chunks of 5 elements:

<code class="language-csharp">List<List<int>> chunks = myList.ChunkBy(5);</code>

The result will be a list of four sublists, each containing five elements.

Method 2: Use loops

Another way is to use a simple loop:

<code class="language-csharp">public static List<List<T>> SplitList<T>(List<T> list, int chunkSize)
{
    List<List<T>> chunks = new List<List<T>>();

    while (list.Count > 0)
    {
        List<T> chunk = new List<T>(chunkSize);
        for (int i = 0; i < chunkSize && list.Count > 0; i++)
        {
            chunk.Add(list[0]);
            list.RemoveAt(0);
        }
        chunks.Add(chunk);
    }

    return chunks;
}</code>

This method accepts a list and the desired chunk size as arguments, creates a new list of lists, and iterates over the input list, adding chunkSize elements to each new sublist until the input list is empty.

Both methods can effectively split the list into sublists of a specified size. Choose the method that best suits your specific needs and coding style.

The above is the detailed content of How to Efficiently Split a List into Smaller Sublists of a Defined Size?. For more information, please follow other related articles on the PHP Chinese website!

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