LINQ:获取分为子序列的数字序列的最小值和最大值 [英] LINQ: Get min and max values of sequence of numbers divided into subsequences

查看:106
本文介绍了LINQ:获取分为子序列的数字序列的最小值和最大值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何将数字序列分成数字子组并使用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?

如果我有一个序列,可以说11个项目{3,2,5,9,9,9,6,7,2,5,11,2}
我想将其划分为3个或更少项目的子组.

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.

所以我得到以下4个子组:{3,2,5},{9,9,6},{7,2,5},{11,2}

So I get the following 4 subgroups: { 3, 2, 5 } , { 9, 9, 6 } , { 7, 2, 5} , { 11, 2}

LinQ表达式的最终返回值(每个组的最小值和最大值)应为2、5、6、9、2、7、2、11

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, 萨沙

推荐答案

这应该做到.

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;

这篇关于LINQ:获取分为子序列的数字序列的最小值和最大值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆