📒 갈무리 - tuple
📌 tuple
- 튜플은 간단한 데이터 구조에서 여러 데이터 요소를 그룹화하는 기능
- 두 개 이상의 타입을 그룹화해서 사용할 때 클래스나 구조체를 정의하지않고 곧바로 사용할 수 있다.
📌 클래스 튜플 타입
Tuple<int, float> tuple1 = new Tuple<int, float>(1, 1.5f);
Tuple<int, float, int, int, int, int, int, int> tuple2 =
new Tuple<int, float, int, int, int, int, int, int>(10, 2.5f, 10, 10, 10, 10, 10, 10);
- 클래스 타입이므로 전달할 때 복사를 하지 않고, 참조값을 전달한다.
- 내부 값들은 프로퍼티로 존재한다.
📌 구조체 튜플 타입
ValueTuple<int, float> tuple1 = (3, 2.5f);
(int, float, string) tuple2 = (2, 1.5f, "def");
var t3 = (3, 2.5f, "ghi");
- 구조체 타입이므로 전달할 때 복사되어 전달된다.
- 내부 값들은 필드로 존재한다.
📌 튜플 접근
var t = (num1: 3, num2: 2.5f, word: "ghi");
Console.WriteLine($"t : {t}");
Console.WriteLine($"t : {t.Item1}, {t.Item2}, {t.Item3}");
Console.WriteLine($"t1 : {t.ToString()}");
Console.WriteLine($"t2 : {t.num1}, {t.num2}, {t.word}");
Output:
t : (3, 2.5, ghi)
t : 3, 2.5, ghi
t1 : (3, 2.5, ghi)
t2 : 3, 2.5, ghi
📌 튜플 할당 및 분해
튜플 할당 조건
- 두 튜플의 요소 수가 동일함
- 오른쪽 튜플 요소의 형식이 해당하는 왼쪽 튜플 요소의 형식과 동일하거나 해당 형식으로 암시적 변환이 가능함
(int, double) t1 = (10, 3.14);
(double First, double Second) t2 = (0.0, 1.0);
t2 = t1;
Console.WriteLine($"{nameof(t2)}: {t2.First} and {t2.Second}");
var t = ("post office", 3.6);
(string destination, double distance) = t;
Console.WriteLine($"Distance to {destination} is {distance} kilometers.");
var t = ("post office", 3.6);
var (destination, distance) = t;
Console.WriteLine($"Distance to {destination} is {distance} kilometers.");
var destination = string.Empty;
var distance = 0.0;
var t = ("post office", 3.6);
(destination, distance) = t;
Console.WriteLine($"Distance to {destination} is {distance} kilometers.");
📌 튜플 같음
(int a, byte b) left = (5, 10);
(long a, int b) right = (5, 10);
Console.WriteLine(left == right);
Console.WriteLine(left != right);
var t1 = (A: 5, B: 10);
var t2 = (B: 5, A: 10);
Console.WriteLine(t1 == t2);
Console.WriteLine(t1 != t2);
다음 조건이 충족되면 두 튜플 비교가 가능
- 두 튜플의 요소 수가 동일
- 각 튜플 위치에서 왼쪽 및 오른쪽 튜플 피연산자의 해당 요소는 == 및 != 연산자와 비교할 수 있다. 예를 들어 1은 (1, 2)와 비교할 수 없기 때문에 (1, (2, 3)) == ((1, 2), 3)은 컴파일되지 않는다.