Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Linq: How to group by maximum number of items

Tags:

c#

linq

grouping

CONTEXT

  • I have a list of items (or arbitrary length). I'd like to group them in 'chunks' of a certain size
  • Example: I have 12 customers [0,1,2,3,4,5,6,7,8,9,10,11] and want to group themin chunks of 5 which would give [0,1,2,3,4] [5,6,7,8,9] [10,11]
  • NOTE: In reality I am not working with customers or monotonically increasing integers. I picked that just to simplify asking the question

MY QUESTION

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

BACKGROUND

  • I'm already familiar with how to use LINQ syntax for grouping by a value for example (to group sales by customer id), however I am at a loss how to express the 'chunking' cleanly/elegantly using LINQ. I am not sure if it is even possible in a straightforward way.
  • I can and have already implemented a solution in plain-old-C# without using the LINQ syntax. Thus, my problem is not being blocked on this question, but rather I am looking for ways to express it in LINQ (again cleanly and elegantly)
like image 346
namenlos Avatar asked Aug 11 '09 02:08

namenlos


2 Answers

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());
}
like image 118
frakon Avatar answered Sep 20 '22 08:09

frakon


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())
like image 41
Jesse Avatar answered Sep 17 '22 08:09

Jesse