And*_*are 140
你可以使用Enumerable.Max
:
new [] { 1, 2, 3 }.Max();
Run Code Online (Sandbox Code Playgroud)
Jon*_*eet 126
好吧,你可以叫它两次:
int max3 = Math.Max(x, Math.Max(y, z));
Run Code Online (Sandbox Code Playgroud)
如果你发现自己做这个有很多,你可以编写自己的辅助方法......我会很愿意在我的代码库看到这一次,但不经常.
(请注意,这可能比安德鲁基于LINQ的答案更有效 - 但显然你拥有的元素越多,LINQ方法就越有吸引力.)
编辑:"两全其美"的方法可能是有一套自定义方法:
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);
}
}
Run Code Online (Sandbox Code Playgroud)
这样你就可以编写MoreMath.Max(1, 2, 3)
或MoreMath.Max(1, 2, 3, 4)
不编写数组创建的开销,但是MoreMath.Max(1, 2, 3, 4, 5, 6)
当你不介意开销时,仍然可以编写可读且一致的代码.
我个人发现它比LINQ方法的显式数组创建更具可读性.
Bas*_*Bas 29
Linq具有Max功能.
如果你有,IEnumerable<int>
你可以直接调用它,但如果你需要在单独的参数中,你可以创建一个这样的函数:
using System.Linq;
...
static int Max(params int[] numbers)
{
return numbers.Max();
}
Run Code Online (Sandbox Code Playgroud)
然后你可以像这样调用它:max(1, 6, 2)
它允许任意数量的参数.
Her*_*eld 12
作为通用
public static T Min<T>(params T[] values) {
return values.Min();
}
public static T Max<T>(params T[] values) {
return values.Max();
}
Run Code Online (Sandbox Code Playgroud)
关于主题,但这里是中间价值的公式..以防万一有人正在寻找它
Math.Min(Math.Min(Math.Max(x,y), Math.Max(y,z)), Math.Max(x,z));
Run Code Online (Sandbox Code Playgroud)
让我们假设你有一个List<int> intList = new List<int>{1,2,3}
如果你想获得最大值你可以这样做
int maxValue = intList.Max();
Run Code Online (Sandbox Code Playgroud)
归档时间: |
|
查看次数: |
99409 次 |
最近记录: |