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