简体   繁体   English

C# - 如何找到最低和最高数字之间的差异

[英]C# - How to find a difference between lowest and highest numbers

I have a List that contains multiple numbers like this:我有一个包含多个数字的列表,如下所示:

  • 1.75 1.75
  • 1.25 1.25
  • 2.03 2.03
  • 1.44 1.44

What I want to do, is to find a difference between lowest and highest number.我想要做的是找到最低最高数字之间的差异。 In this case it would be 1.25 and 2.03 , which would make 0.78 .在这种情况下,它将是1.252.03 ,这将使0.78

How should I do it?我该怎么做?

The steps are quite simple:步骤非常简单:

  1. Find the largest number in the list找到列表中最大的数字
  2. Find the smallest number in the list找出列表中最小的数字
  3. The result you need = [Result of 1] - [Result of 2]您需要的结果 = [结果 1] - [结果 2]

To implement this you can use LINQ:要实现这一点,您可以使用 LINQ:

// Intialize your list (or use the existing one)
var list = new List<decimal>{ 1.75m, 1.25m, 2.03m, 1.44m};
// The result is maximum of the list minus minimum of the list
var result = list.Max() - list.Min();
// Print or use the result
Console.WriteLine(result);  // prints the result 0.78

首先确定最大值和最小值,然后从最大值中减去最小值。

There are a few different ways you can do it, but first a few questions:有几种不同的方法可以做到这一点,但首先要问几个问题:

  1. Is the list sorted?列表是否排序? If it is, then it's really simple.如果是,那真的很简单。
  2. If it's not sorted, then you may iterate through the list, an have two variables "min" and "max", and in the end just find the difference.如果它没有排序,那么你可以遍历列表,有两个变量“min”和“max”,最后找到差异。
  3. Are you given the list?给你名单了吗? If not and you are the one adding values to the list, then you can keep track of the added values, and assign them appropriately to your "min" and "max" variables.如果不是,并且您是向列表添加值的人,那么您可以跟踪添加的值,并将它们适当地分配给您的“min”和“max”变量。
  4. You can use LINQ您可以使用 LINQ

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM