본문 바로가기

프로그래밍/C#

[C#] LINQ 집계 작업, 표준 쿼리 연산자

반응형

표준 쿼리 연산자는 LINQ 패턴을 형성하는 메서드입니다.

집계 작업은 컬렉션을 특정 조건으로 계산하여 하나의 값을 출력합니다.

예를 들어 1달 동안 일일 온도 값을 기록한 컬렉션에서 평균 온도를 계산한다던지, 학생들의 성적을 기록한 컬렉션에서 가장 점수가 높은 학생을 찾는 작업을 수행할 수 있습니다.

이러한 작업을 집계 작업이라고 하며, LINQ에서는 집계 작업을 위해 'Aggregate, Average, Count, Max, Min, Sum'함수를 지원하고 있습니다. 이번 글에서는 이중에서 'Aggregate'에 대해서만 설명해보고자 합니다. 집계 작업이 전체적으로 간단하기도 하고, Aggregate 가장 어려우면서 가장 많이 사용하는 함수이기 때문입니다. Aggregate에 대해 설명하기 전, 집계 작업의 메서드들을 간단히 정리해보도록 하겠습니다.

 

Aggregate - 컬렉션 값에 대해 사용자 지정 집계 작업을 수행합니다.

Average - 값 컬렉션의 평균 값을 계산합니다.

Count - 컬렉션에서 조건에 충족하는 요소의 개수를 계산합니다.

Max - 컬렉션에서 최대값을 확인합니다.

Min - 컬렉션에서 최소값을 확인합니다.

Sum - 컬렉션에 있는 값의 합계를 계산합니다.

 

 


 

Aggregate

- 시퀀스에 누적기 함수를 적용합니다.

- 시드 값은 초기 누적기 값으로 사용되고 지정된 함수는 결과 값을 선택하는 데 사용됩니다.

 

 

 

예제 1 : 소스코드

            // 예제 1
            Console.WriteLine("예제 1 :");
            var nums = Enumerable.Range(1, 5);
            var sum = nums.Aggregate((a, b) => a + b);
            Console.WriteLine(sum);
            Console.WriteLine("---------------\n");
            // 출력값 : 15

 

 

예제 1 : 실행결과

15

 

 

nums에 1부터 5까지의 정수를 가지는 컬렉션을 만든 후,

Aggregate를 이용하여 이 모든 숫자를 더하는 작업을 진행하였습니.

실행결과는 1+2+3+4+5 의 값을 계산하여 15가 출력됩니다.

 

 

 

 

 

예제 2 : 소스코드

            // 예제 2
            Console.WriteLine("예제 2 :");
            var chars = new[] { "a", "b", "c" }; // char로 저장시 +연산자 적용불가
            var csv = chars.Aggregate((a, b) => a + ',' + b);
            Console.WriteLine(csv);
            Console.WriteLine("---------------\n");
            // 출력값 : a,b,c

 

 

예제 2 : 실행결과

a,b,c

 

문자열들을 엑셀들에서 쉽게 불러올 수 있는 csv형태로 저장하는 예제입니다.

문자(a)와 문자(b) 사이 쉼표를 추가하여(a+','+b) csv 변수에 저장하는 작업을 진행합니다.

 

 

 

 

 

 

예제 3 : 소스코드

            // MSDN 예제 1
            Console.WriteLine("MSDN 예제 1 :");
            string[] fruits = { "apple", "mango", "orange", "passionfruit", "grape" };

            // Determine whether any string in the array is longer than "banana".
            string longestName =
                fruits.Aggregate("banana",
                                (longest, next) => {
                                    Console.WriteLine("next    : " + next);
                                    Console.WriteLine("longest : " + longest);
                                    Console.WriteLine("-");
                                    return next.Length > longest.Length ? next : longest;
                                },
                                // Return the final result as an upper case string.
                                fruit => fruit.ToUpper());

            Console.WriteLine(
                "The fruit with the longest name is {0}.",
                longestName);
            // This code produces the following output:
            //
            // The fruit with the longest name is PASSIONFRUIT.
            Console.WriteLine("---------------\n");

 

 

예제 3 : 실행결과

 

 

 

MSDN에서 제공하는 예제를 해석하기 좋게 수정하여 출력해보았습니다.

Aggregate의 익명함수 안에 작성된 'WriteLine'문과 출력 값을 비교해보면

Aggregate의 작동방법에 대해 쉽게 이해할 수 있을 것입니다.

 

이 예제는 문자열의 length값을 비교하여 컬렉션에서 가장 긴 문자열을 찾는 코드입니다.

Aggregate의 seed값 'banana'를 시작으로, fruits컬렉션의 'apple'부터 'grape'까지 순서대로 문자열의 길이를 비교하며 가장 긴 문자열을 검색합니다.

 

 

 

 

 

예제 4 : 소스코드

            // MSDN 예제 2
            Console.WriteLine("MSDN 예제 2 :");
            int[] ints = { 4, 8, 8, 3, 9, 0, 7, 8, 2 };

            // Count the even numbers in the array, using a seed value of 0.
            int numEven = ints.Aggregate(0, (total, next) => {
                Console.WriteLine("total : " + total);
                Console.WriteLine("next  : " + next);
                Console.WriteLine("-");
                return next % 2 == 0 ? total + 1 : total;
            });

            Console.WriteLine("The number of even integers is: {0}", numEven);

            // This code produces the following output:
            //
            // The number of even integers is: 6
            Console.WriteLine("---------------\n");

 

 

예제 4 : 실행결과

 

int형 컬렉션에서 짝수의 숫자를 계산하는 예제입니다.

마찬가지로 익명함수와 실행결과를 비교하면 쉽게 이해할 수 있을것입니다.

 

 

 

 

예제 5 : 소스코드

            // MSDN 예제 3
            Console.WriteLine("MSDN 예제 3 :");
            string sentence = "the quick brown fox jumps over the lazy dog";

            // Split the string into individual words.
            string[] words = sentence.Split(' ');

            // Prepend each word to the beginning of the
            // new sentence to reverse the word order.
            string reversed = words.Aggregate((workingSentence, next) =>
            {
                Console.WriteLine("workingSentence : " + workingSentence);
                Console.WriteLine("next            : " + next);
                Console.WriteLine("-");
                return next + " " + workingSentence;
            });

            Console.WriteLine(reversed);

            // This code produces the following output:
            //
            // dog lazy the over jumps fox brown quick the

 

 

 

예제 5 : 실행결과

 

 

띄어쓰기(' ')를 기준으로 문자열을 나누고, 그 나눠진 문자열의 숫자를 반대로 출력하는 예제입니다.

'the quick brown fox jumps over the lazy dog' 라는 문자열을 입력했을 시

'dog lazy the over jumps fox brown quick the' 라는 결과가 출력됩니다.

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

Enumerable.Aggregate 메서드 (System.Linq)

시퀀스에 누적기 함수를 적용합니다.Applies an accumulator function over a sequence. 지정된 시드 값은 초기 누적기 값으로 사용되고 지정된 함수는 결과 값을 선택하는 데 사용됩니다.The specified seed value is

docs.microsoft.com

반응형