开发者

LINQ: Get min and max values of sequence of numbers divided into subsequences

开发者 https://www.devze.com 2023-01-21 08:41 出处:网络
how can I split a sequence of numbers into subgroups of numbers and get the local minimum and maximum of the subgroups with linq?

how can I split a sequence of numbers into subgroups of numbers and get the local minimum and maximum of the subgroups with linq?

If I have a sequence of, lets say 11 items { 3, 2, 5, 9, 9, 6, 7, 2, 5, 11, 2 }

I want to split this into subgroups with 3 or less items.

So I get the following 4 subgroups: { 3, 2, 5 } , { 9, 9, 6 开发者_Python百科} , { 7, 2, 5} , { 11, 2}

The final return values of the LinQ expression (getting min and max for each group) should be 2, 5, 6, 9, 2, 7, 2, 11

TIA, Sascha


This should do it.

var numbers = new[] { 3, 2, 5, 9, 9, 6, 7, 2, 5, 11, 2 };
var query = from p in numbers.Select((n, i) => new { n, Group = i / 3 })
            group p.n by p.Group into g
            from n in new[] { g.Min(), g.Max() }
            select n;


Well, using MoreLINQ's Batch method to do the grouping, you could use:

var query = source.Batch(3, batch => new[] { batch.Min(), batch.Max() })
                  .SelectMany(x => x);
0

精彩评论

暂无评论...
验证码 换一张
取 消