这个方法应该像 Math.Max()
一样工作,但是接受三个或更多的 int
参数。
你可以使用Enumerable.Max
方法:
new [] { 1, 2, 3 }.Max();
[]
创建一个可枚举对象。很棒。 - Mateen Ulhaqnew int[] { 1,2,3 }
的简写形式。因此,它是由内容隐式确定类型的int数组。 - Mixxiphoid好的,你可以直接调用两次:
int max3 = Math.Max(x, Math.Max(y, z));
如果你经常发现自己这样做,你可以编写自己的帮助方法...我很高兴在我的代码库中看到这一点一次,但不是经常性地。
(请注意,这可能比安德鲁(Andrew)基于LINQ的答案更有效率 - 但显然,你拥有的元素越多,LINQ方法就越有吸引力。)
编辑(EDIT):一个“两全其美”的方法可能是无论哪种方式,都有一套自定义的方法:
public static class MoreMath
{
// This method only exists for consistency, so you can *always* call
// MoreMath.Max instead of alternating between MoreMath.Max and Math.Max
// depending on your argument count.
public static int Max(int x, int y)
{
return Math.Max(x, y);
}
public static int Max(int x, int y, int z)
{
// Or inline it as x < y ? (y < z ? z : y) : (x < z ? z : x);
// Time it before micro-optimizing though!
return Math.Max(x, Math.Max(y, z));
}
public static int Max(int w, int x, int y, int z)
{
return Math.Max(w, Math.Max(x, Math.Max(y, z)));
}
public static int Max(params int[] values)
{
return Enumerable.Max(values);
}
}
那么你可以写 MoreMath.Max(1, 2, 3)
或者 MoreMath.Max(1, 2, 3, 4)
来避免创建数组的开销,但是当你不介意开销时,你仍然可以写 MoreMath.Max(1, 2, 3, 4, 5, 6)
以获得更好的可读性和一致性。MoreMath.Max(x, y, z)
比LINQ方法更易读。 - Jon Skeetpublic static int Max(params int[] values)
? - Navid RahmaniMax(1, 2, 3)
将无故创建一个数组。通过为相对较少的参数提供几个重载,您可以使其更加高效,而不会影响调用者的可读性。 - Jon SkeetLinq有一个Max函数。
如果您有一个 IEnumerable<int>
,则可以直接调用此函数,但如果您需要将它们分开为不同的参数,则可以创建如下的函数:
using System.Linq;
...
static int Max(params int[] numbers)
{
return numbers.Max();
}
那么你可以像这样调用它:max(1, 6, 2)
,它允许传入任意数量的参数。
Max
而不是 max
,并且让它成为静态的 :) 通过减少参数的重载,你也可以使它更高效。 - Jon Skeet作为通用的
public static T Min<T>(params T[] values) {
return values.Min();
}
public static T Max<T>(params T[] values) {
return values.Max();
}
虽然有些偏题,但这里提供中位数的计算公式,以防有人需要。
Math.Min(Math.Min(Math.Max(x,y), Math.Max(y,z)), Math.Max(x,z));
假设您有一个 List<int> intList = new List<int>{1,2,3}
,如果您想要获取最大值,可以执行以下操作:
int max = intList.Max();
int maxValue = intList.Max();
public int Max(int[] values) {
if(values.Length < 1) {
return 0;
}
if(values.Length < 2) {
return values[0];
}
if(values.Length < 3) {
return Math.Max(values[0], values[1]);
}
int runningMax = values[0];
for(int i=1; i<values.Length - 1; i++) {
runningMax = Math.Max(runningMax, values[i]);
}
return runningMax;
}
priceValues[]中的最大元素值为maxPriceValues:
double[] priceValues = new double[3];
priceValues [0] = 1;
priceValues [1] = 2;
priceValues [2] = 3;
double maxPriceValues = priceValues.Max();
private float GetBrightestColor(float r, float g, float b) {
if (r > g && r > b) {
return r;
} else if (g > r && g > b) {
return g;
} else if (b > r && b > g) {
return b;
}
}
你可以使用 if 和 else if 方法来处理三个值,但如果你像这样调用两次 Math.Max 方法会更容易:
Console.WriteLine("Largest of three: " + Math.Max(num1, Math.Max(num2, num3)));
Console.WriteLine("Lowest of three: " + Math.Min(num1, Math.Min(num2, num3)));