Linq: How to group by maximum number of items

2019-04-26 14:14发布

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)

标签: c# linq grouping
4条回答
Bombasti
2楼-- · 2019-04-26 14:30

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;
查看更多
女痞
3楼-- · 2019-04-26 14:37

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);
查看更多
萌系小妹纸
4楼-- · 2019-04-26 14:44

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());
}
查看更多
走好不送
5楼-- · 2019-04-26 14:49

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())
查看更多
登录 后发表回答