Home >Backend Development >C++ >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
<code>[a, g, e, w, p, s, q, f, x, y, i, m, c]</code>
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>
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>
According to the index group
GroupBy
Select the sub -list sublistSize
: Select
to convert the group into a list. 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!