namenlos
namenlos

Reputation: 5181

Linq: How to group by maximum number of items

CONTEXT

MY QUESTION

How can I formulate a straightforward LINQ query (using query syntax) that performs this grouping?

BACKGROUND

Upvotes: 13

Views: 5769

Answers (4)

Jesse
Jesse

Reputation: 8749

For those who prefer the LINQ methods (with lambda expressions), here is Dimitriy Matveev's answer converted:

var result = array
    .Select((value, index) => new { Value = value, Index = index })
    .GroupBy(i => i.Index / chunkSize, v => v.Value);

If you need just an array of value, instead of an IGrouping<T1, T2>, then append the following:

.Select(x => x.ToArray())

Upvotes: 4

frakon
frakon

Reputation: 2273

Extension method (using Jesse's answer):

public static IEnumerable<T[]> GroupToChunks<T>(this IEnumerable<T> items, int chunkSize)
{
    if (chunkSize <= 0)
    {
        throw new ArgumentException("Chunk size must be positive.", "chunkSize");
    }

    return
        items.Select((item, index) => new { item, index })
             .GroupBy(pair => pair.index / chunkSize, pair => pair.item)
             .Select(grp => grp.ToArray());
}

Upvotes: 1

Steven Creaney
Steven Creaney

Reputation: 45

To do the actual grouping, shouldn't it be:

var result = array
.Select((value, index) => new { Value = value, Index = index})
.GroupBy(i => i.Index / chunk, v => v.Value);

Upvotes: 0

okutane
okutane

Reputation: 14250

You can group them by (index/chunkSize). Example:

    var result =
        from i in array.Select((value, index) => new { Value = value, Index = index })
        group i.Value by i.Index / chunkSize into g
        select g;

Upvotes: 13

Related Questions