Home >Backend Development >C++ >How Can I Efficiently Chunk a List into Sublists of a Specific Size in C#?

How Can I Efficiently Chunk a List into Sublists of a Specific Size in C#?

DDD
DDDOriginal
2025-01-18 04:41:07727browse

How Can I Efficiently Chunk a List into Sublists of a Specific Size in C#?

Dividing a List into Smaller Sublists of a Specified Size in C#

The original splitList function aimed to break down a list into smaller lists, each containing 30 elements. However, it had flaws resulting in sublists of inconsistent sizes.

Improved Solution using an Extension Method:

A more robust approach involves creating a C# extension method:

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

Functionality Explained:

This extension method efficiently chunks a list (source) into sublists of a given chunkSize. It leverages LINQ:

  1. Indexing and Value Pairing: Select((x, i) => new { Index = i, Value = x }) creates an anonymous type containing each element's index and value.

  2. Grouping by Chunk: GroupBy(x => x.Index / chunkSize) groups elements based on their index divided by the chunkSize. This ensures elements within the same chunk are grouped together.

  3. List Creation: Select(x => x.Select(v => v.Value).ToList()) converts each group back into a list of the original element type.

  4. Final List of Lists: ToList() creates the final list containing the chunked sublists.

Practical Application:

To use this method to create sublists of size 30 from a list named locations:

<code class="language-csharp">List<List<YourElementType>> chunkedLists = locations.ChunkBy(30);</code>

Illustrative Example:

If locations contains 144 elements, chunkedLists will correctly contain 5 sublists with sizes: 30, 30, 30, 30, and 24.

Future C# Enhancement:

Note that .NET 6 introduces a built-in Chunk method for this purpose, simplifying the process further:

<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 Chunk a List into Sublists of a Specific Size in C#?. 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