[C# 문법] Linq Aggregate vs String.Join

참고


개요

  • C# 에서 문자열을 합치는 방법이 크게는 Linq 를 이용하여 Aggregate 를 이용하거나 혹으 String.Join 함수를 이용하여 문자열을 합칠 수 있습니다.
  • 오늘은 Aggregate 와 String.Join 함수 사용하는 방법과 둘의 차이점은 무엇인지에 대해 알아보려고 합니다.

Linq Select 구문으로 문자열 출력하기

  • 다음 코드는, Linq Select 구문으로 문자열 합치는 방법입니다.
// create a collection of objects to play with
var myEntities = Enumerable.Range(0, 5).Select(x => new {Id = x});

// extract the IDs from the entities
var idStrings = myEntities.Select(e => e.Id.ToString());

// idStrings: "0", "1", "2", "3", "4"

Linq Aggregate 구문으로 문자열 합치기

  • 다음은 Linq Aggregate 구문으로 "," 구문으로 문자열을 합치는 코드입니다.
var myEntities = Enumerable.Range(0, 5).Select(x => new {Id = x});

// extract the IDs from the entities, then join them into a single string
var idString = myEntities.Select(e => e.Id.ToString()).Aggregate((c, n) => $"{c},{n}");

// idString: "0,1,2,3,4"
  • 위 방법은 꽤 괜찮은 방법입니다.
  • 하지만, Aggregate 의 가장 큰 문제는, Entity Collection 이 비어 있으면 InvalidOperationException 예외를 발생하는 문제가 있습니다.
// create an empty collection using Enumerable.Range(0, 0) 
var myEntities = Enumerable.Range(0, 0).Select(x => new {Id = x});

// extract the IDs from the entities
var idStrings = myEntities.Select(e => e.Id.ToString());

// throws System.InvalidOperationException - Sequence contains no elements
var idString = idStrings.Aggregate((c, n) => $"{c},{n}");
  • 하지만, Aggregate 에서 seed 데이터를 사전에 제공하게 되면, 위 문제를 해결할 수는 있습니다.
// create an empty collection using Enumerable.Range(0, 0) 
var noEntities = Enumerable.Range(0, 0).Select(x => new {Id = x});

// string.Empty seed string prevents the exception
var seed = string.Empty;
var emptyIdString = noEntities.Select(e => e.Id.ToString()).Aggregate(seed, (c, n) => $"{c},{n}");

// emptyIdString: ""

// BUT if you have items in your collection...
var myEntities = Enumerable.Range(0, 5).Select(x => new {Id = x});

// then you end up with a comma at the beginning of your string
var idString = myEntities.Select(e => e.Id.ToString()).Aggregate(seed, (c, n) => $"{c},{n}");

// idString: ",0,1,2,3,4"
  • 위와 같이 seed 데이터를 선언하여, InvalidOperationException 예외를 방지할 수 있습니다.
  • 하지만, 위와 같이 보기에 코드의 양이 커지면서 가독성이 떨어져 보이는 단점이 있습니다.
  • String.Join 함수를 이용하여 위 내용과 동일하게 출력하는 코드를 작성해 보겠습니다.

String.Join 메서드 사용

// create an empty collection using Enumerable.Range(0, 0) 
var myEntities = Enumerable.Range(0, 0).Select(x => new { Id = x });

// extract the IDs from the entities
var idStrings = myEntities.Select(e => e.Id.ToString());

// join the strings
var idString = string.Join(",", idStrings);

// idString: ""
  • 위와 같이 Aggregate 가 아닌 String.Join 함수를 이용하여 동일한 결과 값을 출력할 수도 있습니다.
728x90

이 글을 공유하기

댓글

Designed by JB FACTORY