본문 바로가기
C++ 200제/코딩 IT 정보

C# 6.0 Statement Lambda로 문자열 보간 기능 구현 예제 (람다 소스)

by vicddory 2019. 4. 1.

C# 6.0으로 구현하는 문자열 보간

조건문에 Lambda 람다 추가하여 string Interpolation 구현



프로그래밍 언어에서 조건문이란 조건을 처리하는 과정(소스 코드)입니다. if~else, switch~case, 삼항 조건 연산자(Ternary Operators)는 람다로 대체하거나 섞어서 사용할 수 있습니다. 이 예제에서 몇 가지 구체적인 예제로 문자열 보간 방법을 알아보겠습니다.




예제 1 : Statement Lambda와 if~else 응용


어떤 사람이 투표에 참여할 수 있는지 확인하는 예제를 C# 6.0 〈스테이트먼트 람다〉로 구현합니다.


1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
using System;
using System.Collections.Generic;
using System.Linq;
 
namespace ConsoleApplication1
{
    class Program
    {
        static void Main(string[] args)
        {
            var personData = new List<PersonMaster>();
 
            //populating some data
            Enumerable
                .Range(110)
                .ToList()
                .ForEach(
                            i =>
                            personData.Add(new PersonMaster
                            {
                                PersonID = i,
                                PersonName = string.Concat("Person ", i),
                                Age = 14+i
                            })
                        );
 
            //Use of Statement Lambda
            var eligiblePersonData = new List<EligiblePerson>();
 
            personData
                .ToList()
                .ForEach(i =>
                {
                    if (i.Age < 18)
                        Console.WriteLine("Mr. {0} is not eligible to case vote as his age is {1} which is under 18",i.PersonName,i.Age);
                    else
                        eligiblePersonData.Add(new EligiblePerson
                        {
                            PersonID = i.PersonID,
                            PersonName = i.PersonName,
                            Age = i.Age
                        });
                  });
 
            Console.ReadKey();
        }
    }
 
    //The main person model
    public class PersonMaster
    {
        public int PersonID { get; set; }
        public string PersonName { get; set; }
        public int Age { get; set; }
 
    }
 
    //Eligible Person Model
    public class EligiblePerson
    {
        public int PersonID { get; set; }
        public string PersonName { get; set; }
        public int Age { get; set; }
    }   
}
cs


다음 그림에서 알 수 있듯이 if ~ else 구간을 Statement Lambda로 대체하여 문자열 합치기가 가능합니다.


C# 6.0 문자열 보간을 조건문 람다로 처리 예제 (Interpolation Lambda)[닷넷 문자열 선형 보간, string format]


스테이트먼트 람다가 적용된 영역입니다.



예제 2 : 삼항 연산자와 Statement Lambda 응용


1번 예제와 비슷하지만 삼항 연산자 ternary operator를 사용한 소스입니다.


1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
personData
        .ToList()
        .ForEach(i =>
        {
 
           switch(i.Age < 18 ? 0:1// note the way the ternary operator is used inside the switch statement as an expression
            {
                case 0:
                    Console.WriteLine("Mr. {0} is not eligible to case vote as his age is {1} which is under 18", i.PersonName, i.Age);
                    break;
                case 1:
                    eligiblePersonData.Add(new EligiblePerson
                    {
                        PersonID = i.PersonID,
                        PersonName = i.PersonName,
                        Age = i.Age
                    });
                    break;
            }
        });
cs


람다 코드 자체는 if~else 문과 똑같습니다.




C# 6.0 문자열 보간 사용 방법


위의 코드를 C# 6.0의 String Interpolation로 다시 구현합니다.


1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
switch (i.Age < 18 ? 0 : 1)
{
    case 0:
 
       //note the usage of String Interpolation - a feature of C# 6.0 
 
        string toDisplay = $"Mr. {i.PersonName}   is not eligible to case vote as his age is {i.Age}  which is under 18";
        Console.WriteLine(toDisplay); 
        break;
    case 1:
        eligiblePersonData.Add(new EligiblePerson
        {
            PersonID = i.PersonID,
            PersonName = i.PersonName,
            Age = i.Age
        });
        break;
}
cs



C# 6.0에는 문자열 사이를 이어주는 보간 기능이 따로 있습니다. 실제 프로퍼티를 아래와 같이 사용하는 것입니다.


【  {i.PersonName}  】

【  {i.Age}  】


이렇게 사용할 경우 새로운 문자열을 보간할 땐 $ 기호를 붙여야 합니다.


런타임 단계에서 {i.PersonName}은 프로퍼티 값이 대입됩니다.


c# 문자열 합치기 추가하기 보간[닷넷 문자열 선형 보간, string format]


IL 컴파일 시기 {i.PsersonName}을 System.String으로 호출하는 것이 확인됩니다. String Interpolation은 string.Format 함수를 호출하기 위해 컴파일러가 생성하는 일종의 속임수(trick)과도 같습니다.




위의 예제를 실행하면 결과는 다음과 같습니다.


c# 6.0 string 람다 보간[닷넷 문자열 선형 보간, string format]



첨부 파일


C# 6.0으로 구현하는 문자열 보간

조건문에 Lambda 람다 추가하여 string Interpolation 구현

댓글