namenlos namenlos - 1 year ago 89
C# Question

Linq: How to group by maximum number of items


  • 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


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


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

Answer Source

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;
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download