튜플을 단일 값으로 처리

    MinMax 메서드의 다른 부분도 살펴보자. 다음은 MinMax 메서드 내에서 result.minresult.max에 새로운 값을 할당하는 부분이다.

    result.min = Math.Min(result.min, iterator.Current);
    result.max = Math.Max(result.max, iterator.Current);

    코드를 이처럼 작성하지 않고, 다음과 같이 result와 단일의 할당 문만 이용할 수도 있다.

    예제 11-4 MinMax 메서드 내에서 결과 튜플의 값을 재할당하는 코드 ▶ MinMax3.cs

    static (int min, int max) MinMax(IEnumerable<int> source)
    {
        using (var iterator = source.GetEnumerator())
        {
            if (!iterator.MoveNext())
            {
                throw new InvalidOperationException(
                    "Cannot find min/max of an empty sequence");
            }
            var result = (min: iterator.Current, max: iterator.Current);
            while (iterator.MoveNext())
            {
                result = (Math.Min(result.min, iterator.Current),
                          Math.Max(result.max, iterator.Current));
            } 
            return result;
        }
    }

     


    ➊ result에 새로운 값을 할당
    신간 소식 구독하기
    뉴스레터에 가입하시고 이메일로 신간 소식을 받아 보세요.