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>
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>
ResultList will include the following lists:
<code class="language-csharp">List<List<string>> resultList = Split(originalList);</code>
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>
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!