본문 바로가기

Develop/.NET 가이드

[C#] LINQ 사용방법 - 집계 작업 Aggregate

반응형

LINQ
LINQ

집계 작업 Aggregators

집계 작업은 집합 모든 요소를 계산하여 하나의 값으로 반환하는 작업입니다. 집계 작업에 해당하는 LINQ 메서드로는 Count, Sum, Min, Max, Average, Aggregate 가 있습니다.

Aggregate

Enumerable.Aggregate 메서드는 영어를 모국어로 사용하지 않는 개발자에겐 직관적으로 와닿지 않는 메서드입니다.

영단어 Aggregate합계, 총액 이란 뜻으로 직역되지만, 언어적 뉘앙스는 작은 단위가 누적되어 합쳐져 하나를 이루는 느낌입니다.

따라서 Enumerable.Aggregate 메서드는 Enumerable.Sum 메서드와는 다르게 사용됩니다.

기본적인 사용방법

            double[] doubles = { 1.7, 2.3, 1.9, 4.1, 2.9 };

            double product = doubles.Aggregate((runningProduct, nextFactor) => runningProduct * nextFactor);

            // product = 88.33080999999999
            string[] fruits = { "apple", "mango", "orange", "passionfruit", "grape" };

            string line = fruits.Aggregate((line, fruit) => line + ", " + fruit);

            // line = apple, mango, orange, passionfruit, grape

Enumerable.Aggregate 메서드는 위 예제와 같이 foreach 문보다 짧고 간결하게 string을 연결하여 문장을 만들 수 있습니다.

조건에 따라 누적시키기

             double startBalance = 100.0;

            int[] attemptedWithdrawals = { 20, 10, 40, 50, 10, 70, 30 };

            double endBalance =
                attemptedWithdrawals.Aggregate(startBalance,
                    (balance, nextWithdrawal) =>
                        ((nextWithdrawal <= balance) ? (balance - nextWithdrawal) : balance));

예제처럼 nextWithdrawal <= balance 결과에 따라 누적시킬지 말지를 결정할 수도 있습니다.

반응형