Home > Backend Development > C++ > How Can LINQ Efficiently Split a List into Sublists of a Specified Size?

How Can LINQ Efficiently Split a List into Sublists of a Specified Size?

Susan Sarandon
Release: 2025-02-01 22:36:13
Original
648 people have browsed it

How Can LINQ Efficiently Split a List into Sublists of a Specified Size?

Use Linq efficient segmentation list

LINQ provides a simple and powerful data processing method for the .NET application, including the function of dividing the list into a sub -list according to various conditions.

Consider the following issues: You have a

, you need to divide it into several sub -lists of the

object, and the size of each child list is determined by the index. For example, the original list contains the following elements: List<T> T

The list you want to get is:
<code>[a, g, e, w, p, s, q, f, x, y, i, m, c]</code>
Copy after login

The size of the sub -list can be specified as a function parameter.
<code>[a, g, e], [w, p, s], [q, f, x], [y, i, m], [c]</code>
Copy after login

A solution using linq is as follows:

This code executes the following steps:
<code class="language-csharp">public static List<List<T>> Split<T>(IList<T> source, int sublistSize)
{
    return source
        .Select((x, i) => new { Index = i, Value = x })
        .GroupBy(x => x.Index / sublistSize)
        .Select(x => x.Select(v => v.Value).ToList())
        .ToList();
}</code>
Copy after login

According to the index group
    :
  1. The method is paid to the elements in the source list according to the element index, each group represents a different sub -list. Parameter control subline size. GroupBy Select the sub -list sublistSize:
  2. The method is used to extract the values ​​in each group into a new list.
  3. Converted to the list list : Then use Select to convert the group into a list.
  4. The result is a , each of which contains the specified elements of the original list, and is divided according to the index of the project. By passing into the parameters, the size of the sub -list can be flexibly controlled. ToList

The above is the detailed content of How Can LINQ Efficiently Split a List into Sublists of a Specified 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