[C# 문법] C# 튜플(Tuple) 사용하기



안녕하세요.

 

오늘은 C#에서 제공해주는 문법인 튜플(Tuple)에 대해서 알아 보려고 합니다.

 

튜플은 C# 7.0에서 새롭게 추가된 기능이라고 합니다.

 

그럼 튜플은 보통 어떨 때 사용할까요?

 

튜플이 나오기 전에는 메서드에서 하나의 값만을 리턴할 수 있었는데요. 이제 C# 7.0이상부터는 튜플을 사용하여 메서드로부터 복수 개의 값들을 리턴할 수 있게 되었습니다.


 

그럼 실제로 C#에서 Tuple을 코드로 어떻게 작성하는지 알아 보도록 하겠습니다.

 

오늘 보여드릴 코드는 ListTuple을 적용하여 1가지 타입의 List를 저장하는 것이 아닌, 여러 타입을 List로 저장해서 출력하는 방법을 알려드리도록 하겠습니다.


예제 코드


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

using System;

using System.Collections.Generic;

using System.Linq;

using System.Text;

using System.Threading.Tasks;

 

namespace TupleTest

{

    class Program

    {

        static void Main(string[] args)

        {

            //튜플로 List<int,string> 형식 선언

            List<Tuple<intstring>> list = new List<Tuple<intstring>>();

 

            list.Add(new Tuple<intstring>(1"삼성전자"));

            list.Add(new Tuple<intstring>(2"현대"));

            list.Add(new Tuple<intstring>(3"아시아나"));

            list.Add(new Tuple<intstring>(4"BOE"));

            list.Add(new Tuple<intstring>(5"LG전자"));

 

            //출력하기

            for(int idx = 0; idx < list.Count; idx++)

            {

                Console.WriteLine("{0} : {1}", list[idx].Item1, list[idx].Item2);

            }

        }

    }

}

 

Colored by Color Scripter

cs


실행 결과



위와 같이 알맞게 저장되고 출력되는 모습을 확인하실 수 있습니다.^^

728x90

이 글을 공유하기

댓글

Designed by JB FACTORY