Math.Max와 비슷하지만 int의 3 개 또는 params를 사용합니까?
감사
답변
글쎄, 당신은 그것을 두 번 호출 할 수 있습니다.
int max3 = Math.Max(x, Math.Max(y, z));
이 작업을 많이 수행하는 경우 항상 자신 만의 도우미 메서드를 작성할 수 있습니다. 내 코드베이스에서이 작업을 한 번 볼 수 있으면 좋겠지 만 규칙적으로는 아닙니다.
(이것은 Andrew의 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);
}
}
이렇게하면 배열 생성의 오버 헤드없이 작성 MoreMath.Max(1, 2, 3)
하거나 작성할 수 MoreMath.Max(1, 2, 3, 4)
있지만 MoreMath.Max(1, 2, 3, 4, 5, 6)
오버 헤드에 신경 쓰지 않아도 읽기 쉽고 일관된 코드를 작성할 수 있습니다.
개인적 으로 LINQ 접근 방식 의 명시 적 배열 생성 보다 더 읽기 쉽습니다.
답변
다음을 사용할 수 있습니다 Enumerable.Max
.
new [] { 1, 2, 3 }.Max();
답변
Linq에는 Max 기능이 있습니다.
가있는 경우 IEnumerable<int>
이를 직접 호출 할 수 있지만 별도의 매개 변수에서 필요한 경우 다음과 같은 함수를 만들 수 있습니다.
using System.Linq;
...
static int Max(params int[] numbers)
{
return numbers.Max();
}
그런 다음 다음과 같이 호출 할 수 있습니다. max(1, 6, 2)
, 임의의 수의 매개 변수를 허용합니다.
답변
일반
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 maxValue = intList.Max();
답변
어떤 이유로 든 (예 : Space Engineers API) System.array에 Max에 대한 정의가 없거나 Enumerable에 대한 액세스 권한이없는 경우 Max of n 값에 대한 솔루션 은 다음과 같습니다.
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;
}
