Home >Backend Development >C++ >How Can LINQ Be Used to Split a List into Sublists Based on Item Index?

How Can LINQ Be Used to Split a List into Sublists Based on Item Index?

Linda Hamilton
Linda HamiltonOriginal
2025-02-01 22:26:14618browse

How Can LINQ Be Used to Split a List into Sublists Based on Item Index?

Divide the list using LINQ into a subjistist

There is a large number of lists, and you want to split it into smaller and easier to handle. LINQ (Language Integrated Query) is a powerful tool that can easily achieve this.

Assignment:

How do you use the

item index as a separate character and divide List into several separate SOMEOBJECT lists? For example, if there are 13 lists, you want to divide into five substatures for three items.

Solution:

The custom functions using LINQ to execute this task are shown below.

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

Explanation:

  1. Group on items with indexes: Select method creates anonymous objects with each item value and index. Next, the Groupby method groups of these objects based on the multiplication of the index 3 (the desired sub -list size).
  2. Convert to a group list: Select method in Groupby converts each group into a list.
  3. conversion from to List: Finally, the Tolist method converts IENUMERABLE & LT; List & gt; to List & LT; List
  4. & gt;.

In the provided example, [a, g, e, w, p, s, q, f, f, f, y, I, m, c, c, c, c, c, c, It is divided into g, e], [w, p, s], [q, f, x], [y, i, m], [c]].

The above is the detailed content of How Can LINQ Be Used to Split a List into Sublists Based on Item Index?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
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