How to get the maximum of more than 2 numbers in Visual C#?

心已入冬 提交于 2019-12-12 19:12:48

问题


I have an array of five numbers and an array of 2 numbers. How would I find out the largest number among these 7 numbers? Is there a method that can make things easier?


回答1:


int[] array1 = { 0, 1, 5, 2, 8 };
int[] array2 = { 9, 4 };

int max = array1.Concat(array2).Max();
// max == 9



回答2:


You can try

decimal max = Math.Max(arr1.Max(), arr2.Max());



回答3:


Straightforward way:

Math.Max(Math.Max(a,b), c)//on and on for the number of numbers you have

using LINQ:

int[] arr1;
int[] arr2;
int highest = (from number in new List<int>(arr1).AddRange(arr2)
               orderby number descending
               select number).First();



回答4:


If you're using 3.5 you could use Linq:

using System.Linq;
var values = new int[] { 1,2,3,4,5 };
var maxValue = values.Max();


来源:https://stackoverflow.com/questions/1811756/how-to-get-the-maximum-of-more-than-2-numbers-in-visual-c

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!