프로그래밍/C#
[C#] LINQ Aggregate Function
큐레이트
2019. 1. 11. 23:30
C# (Linq) Aggregate 함수
collection의 전체 데이터(요소)에 대해 누적 방식의 반복작업을 수행한다.
ex)
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 | using System; using System.Linq; namespace console_20190111 { class Program { static void Main(string[] args) { // MS Example Array string[] fruits = { "apple", "mango", "orange", "passionfruit", "grape" }; // 문자열 사이마다 ", "를 넣어준다. Console.WriteLine(fruits.Aggregate((cur, next) => cur + ", " + next)); // Result : apple, mango, orange, passionfruit, grape } } } |
* Comment
가끔 Aggregate 함수에 대해 해깔려 하시는 분이 계시다
Foreach를 생각해서 결과 값이 "apple, mango, orange, passionfruit, grape, " 이렇게 나와야 되는거 아냐 ? 생각 하실 수 있다.
하지만 Foreach는 마지막 데이터일때도 작업을 하는 반면 Aggregate는 마지막 데이터까지 처리되면 종료된다.
위 코드의 Aggregate 연산
(((("apple" + ", " + "manggo") + ", " + "orange") + ", " + "passionfruit") + ", " + "grape")
컬렉션을 반복해서 누적 해야 될 상황이 필요하다면 활용도가 높아보인다.
반응형