Home > Backend Development > C++ > How Can I Split a List into Sublists of a Specific Size Using LINQ in C#?

How Can I Split a List into Sublists of a Specific Size Using LINQ in C#?

Barbara Streisand
Release: 2025-02-01 22:46:12
Original
872 people have browsed it

How Can I Split a List into Sublists of a Specific Size Using LINQ in C#?

Use Linq to divide the list into a list

In C#, we often encounter situations that need to divide the list into smaller pieces or child lists. One way to achieve this goal is to expand the powerful Linq (language integration query) in C#.

Let's consider the examples you provide. You have a , and you want to create a

or

, so that each generated list contains a certain number of continuous items (for example, 3) in the original list. List<T> List To solve this problem with linq, you can use the following code: List<T>[]

This code first groups the elements in the source list based on the result of the

result. This will group them into
<code class="language-csharp">public static List<List<T>> Split<T>(IList<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
blocks. Then, we use the operator to convert each group to the value list, and use the

operator to create a list of a list. chunkSize chunkSize For example, if you have a original list Select, and ToList as 3, then the produced sub -list will be

,

, [a, g, e, w, p, s, q, f, x, y, i, m, c], chunkSize, [a, g, e]. The size of the generated list is determined by the number of items in the original list and the size specified in the group operation. In general, this LINQ -based solution provides an effective method. It can be divided into lists based on index -based separators. The code has been modified to accept the parameters to make it more common. [w, p, s]

The above is the detailed content of How Can I Split a List into Sublists of a Specific Size Using LINQ in C#?. 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