问题描述
我使用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
你想要的东西,有一种使用更容易的方式,因为它们被设计为在收集工作,这就是我们这里处理:
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的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!