[TIL] 127 [C#] ํํ(Tuple)
์นดํ ๊ณ ๋ฆฌ: Til
Tuple
ํํ(Tuple)
ํํ์ ๊ฐ๋จํ ๋ฐ์ดํฐ๋ฅผ ๊ทธ๋ฃน์ผ๋ก ๋ฌถ์ด ๊ด๋ฆฌ ๋ ๊ฐ์ ๋ฐ์ดํฐ๋ฅผ ์ ์ฅ
ํํ์ ์์๊ฐ ์๋ ๋ฐ์ดํฐ์ ์ปฌ๋ ์
๋ฐ์ดํฐ๋ ์๋ก ๋ค๋ฅธ ๋ฐ์ดํฐ ํ์
์ ๊ฐ์ง ์ ์์ต๋๋ค.(int, string)
์์
ํํ ์ฌ์ฉ ์์
var tuple = (1, "Kim", true);
Console.WriteLine(tuple.Item1); // 1
Console.WriteLine(tuple.Item2); // Kim
Console.WriteLine(tuple.Item3); // true
(int id, string name, bool isActive) user = (1, "Kim", true);
Console.WriteLine(user.id); // 1
Console.WriteLine(user.name); // Kim
Console.WriteLine(user.isActive); // True
ํํ ์ฌ์ฉ ์์ (int,int), ๋ฆฌ์คํธ, ํ
// ํํ ์ฌ์ฉ 1
(int, int) pair = (10, 20);
Console.WriteLine($"First: {pair.Item1}, Second: {pair.Item2}");
// ์ถ๋ ฅ : First: 10, Second: 20
-------------------------------------------------------
// ํํ ์ฌ์ฉ 2 - ๋ช
๋ช
๋ ํํ
(int x, int y) namedPair = (10, 20);
Console.WriteLine($"X: {namedPair.x}, Y: {namedPair.y}");
// ์ถ๋ ฅ : X: 10, Y: 20
-------------------------------------------------------
// ํํ ์ฌ์ฉ 3 - ๋ฆฌ์คํธ
List<(int, int)> pairs = new List<(int, int)>
{
(1, 2),
(3, 4),
(5, 6)
};
foreach (var pair in pairs)
{
Console.WriteLine($"First: {pair.Item1}, Second: {pair.Item2}");
}
// ์ถ๋ ฅ:
// First: 1, Second: 2
// First: 3, Second: 4
// First: 5, Second: 6
// ํํ ์ฌ์ฉ 4 - ํ
Queue<(int, int)> queue = new Queue<(int, int)>();
queue.Enqueue((30, 40));
var (curX, curY) = queue.Dequeue();
int nx = curX;
int ny = curY;
์ก๋ด, ์ผ๊ธฐ?
ํํ๋ ๊ฐ๋จํ ๋ ๊ฐ์ ๋ฐ์ดํฐ ๊ทธ๋ฃน์ ๋ค๋ฃจ๋ ๋ฐ ๋งค์ฐ ์ ํฉํฉ๋๋ค.
๋ ๋ณต์กํ ๋ฐ์ดํฐ ๊ตฌ์กฐ๊ฐ ํ์ํ๋ฉด ํด๋์ค๋ ๊ตฌ์กฐ์ฒด๋ฅผ ์ฌ์ฉํ๋ ๊ฒ๋ ์ข์ ๋ฐฉ๋ฒ์
๋๋ค.
๋๊ธ๋จ๊ธฐ๊ธฐ