C# 12 - Collection Expression
2023. 12. 25. 00:00ㆍCSharp
반응형
Dotnet 8 과 함께 Collection Expression 이라는 유용한 기능이 추가 되었다.
아래 코드를 보자
int[] agesArray = { 10, 15, 20, 35, 45, 70, 100, 150 };
List<int> agesList = new() { 10, 15, 20, 35, 45, 70, 100, 150 };
PrintAgesCount(agesArray);
PrintAgesCount(agesList);
PrintAgesCount(new List<int>());
void PrintAgesCount(IEnumerable<int> ages)
{
Console.WriteLine($"count of age is {ages.Count()} ages");
}
코드를 보면 int[] 와 List<int> 를 초기화 하는 코드가 미묘하게 다름을 알수 있을 것이다.
함수에 int 형의 array 에 대한 빈값을 넣기 위해서 new List<int>() 와 같은 parameter 를 넘겨 줘야 한다.
너무 비 효율적인 코딩 방식이다. (initialize 방식)
그래서 dotnet 8 은 Collection Expresstion 이라는 내용을 통해 다음과 같이 수정하였다.
int[] agesArray = [10, 15, 20, 35, 45, 70, 100, 150];
List<int> agesList = [ 10, 15, 20, 35, 45, 70, 100, 150 ];
PrintAgesCount(agesArray);
PrintAgesCount(agesList);
PrintAgesCount([]);
...
아주 깔끔 한 형태이다.
이와 같은 형태로 변경한 후 spread (..) 연산자와 함께 사용하면 아래와 같은 처리도 가능하다.
string[] vowels = ["a", "e", "i", "o", "u"];
string[] consonants = ["b", "c", "d", "f", "g", "h", "j", "k", "l", "m",
"n", "p", "q", "r", "s", "t", "v", "w", "x", "z"];
string[] alphabet = [.. vowels, .. consonants, "y"];
이제 array 관련 초기화 시에 Collection Expression 을 적극 활용하도록 해보자
관련영상
반응형
'CSharp' 카테고리의 다른 글
Expression Tree (0) | 2023.09.04 |
---|---|
Fleck 을 이용한 WebSocket Server 구현 (with streamjsonrpc) (0) | 2023.03.20 |
WebSocket 에 JsonRPC 및 일반메세지 함께 처리하기 (0) | 2023.03.13 |
.NET Core Console 에서 WebSocket Server 에 JsonRPC 적용하기 (0) | 2023.03.07 |
.NET Core Console 에서 WebSocket Server 만들기 (0) | 2023.03.07 |