如何使用Math.Max​​,Math.Min找到三个最大和三个最小decmicals [英] How to find three largest and three smallest decmicals using Math.Max, Math.Min

查看:532
本文介绍了如何使用Math.Max​​,Math.Min找到三个最大和三个最小decmicals的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我使用Math.Max​​和Math.Min找到以下code中的最大和最小小数:

I'm using Math.Max and Math.Min to find the largest and smallest decimals in the following code:

decimal[] numbers = { d1, d2, d3, d4, d5, d6, d7, d8, d9, d10 };
decimal biggestNumber = numbers.Max();
decimal lowestNumber = numbers.Min();
lblS1Val.Text = biggestNumber.ToString();
lblO1Val.Text = lowestNumber.ToString();

我想真正找到三个最大和三个最小的数字。我可以做到这一点Math.Max​​ /最小?

I'd like to actually find the three largest and three smallest numbers. Can I do that with Math.Max/Min?

推荐答案

虽然你可以使用 Math.Min Math.Max​​ 你想要的东西,有一种使用更容易的方式 LINQ到对象,因为它们被设计为在收集工作,这就是我们这里处理:

While you could use Math.Min and Math.Max for what you want, there is a far easier way using LINQ To Objects, as they are designed to work on collections, which is what we're dealing with here:

var smallestThree = numbers.OrderBy(x => x).Take(3);
var largestThree = numbers.OrderByDescending(x => x).Take(3);

请注意这将返回的IEnumerable< decimel> ,所以如果你想要的ToString ,你可以使用的string.join

Note this will return IEnumerable<decimel>, so if you want to ToString it, you can use string.Join:

lblS1Val.Text = string.Join(", ", largestThree);
lblO1Val.Text = string.Join(", ", smallestThree);

这篇关于如何使用Math.Max​​,Math.Min找到三个最大和三个最小decmicals的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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