Home > Backend Development > C++ > How to Efficiently Split a List into Sublists of Equal Size Using LINQ?

How to Efficiently Split a List into Sublists of Equal Size Using LINQ?

Mary-Kate Olsen
Release: 2025-02-01 22:31:10
Original
714 people have browsed it

How to Efficiently Split a List into Sublists of Equal Size Using LINQ?

Use Linq to divide the list into a list of sub -lists

In programming, it is a common operation to divide the list into a sub -list. In C#, an efficient method is to use the LINQ (Language Integrated Query) function. Let's discuss how to divide the list into a sub -list of equal size.

Assuming you need to divide a list of objects into a sub -list with a size of three. For this, we can use the following code:

This code first associates each element in the list with its index. Subsequently, it paid the elements based on the results of the index from the results of the three. This group creates a list of equal size. Finally, it extracts the values ​​in each group into a list of a list.
<code class="language-csharp">public static List<List<T>> Split<T>(IList<T> source)
{
    return source
        .Select((x, i) => new { Index = i, Value = x })
        .GroupBy(x => x.Index / 3)
        .Select(x => x.Select(v => v.Value).ToList())
        .ToList();
}</code>
Copy after login

In order to explain this process, let us assume that we have the following original list:

By calling the Split function, each group of three elements will be stored in a single list in a list of a list of results:
<code class="language-csharp">List<string> originalList = new List<string> { "a", "g", "e", "w", "p", "s", "q", "f", "x", "y", "i", "m", "c" };</code>
Copy after login

ResultList will include the following lists:
<code class="language-csharp">List<List<string>> resultList = Split(originalList);</code>
Copy after login

Using the simple and efficient syntax of Linq, we demonstrated how to easily divide the list into a sub -list of specified size. This method provides a general solution for various data operation scenarios.
<code>[["a", "g", "e"], ["w", "p", "s"], ["q", "f", "x"], ["y", "i", "m"], ["c"]]</code>
Copy after login

The above is the detailed content of How to Efficiently Split a List into Sublists of Equal Size Using LINQ?. 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