HiveBrain v1.2.0
Get Started
← Back to all entries
patterncsharpCritical

Split List into Sublists with LINQ

Submitted by: @import:stackoverflow-api··
0
Viewed 0 times
withlinqsplitlistsublistsinto

Problem

Is there any way I can separate a List into several separate lists of SomeObject, using the item index as the delimiter of each split?

Let me exemplify:

I have a List and I need a List> or List[], so that each of these resulting lists will contain a group of 3 items of the original list (sequentially).

eg.:

-
Original List: [a, g, e, w, p, s, q, f, x, y, i, m, c]

-
Resulting lists: [a, g, e], [w, p, s], [q, f, x], [y, i, m], [c]

I'd also need the resulting lists size to be a parameter of this function.

Solution

Try the following code.

public static List> Split(IList 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();
}


The idea is to first group the elements by indexes. Dividing by three has the effect of grouping them into groups of 3. Then convert each group to a list and the IEnumerable of List to a List of Lists

Code Snippets

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();
}

Context

Stack Overflow Q#419019, score: 450

Revisions (0)

No revisions yet.