[TIL] 127 [C#] ํŠœํ”Œ(Tuple)

์—…๋ฐ์ดํŠธ:

์นดํ…Œ๊ณ ๋ฆฌ:

ํƒœ๊ทธ: ,


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;





์žก๋‹ด, ์ผ๊ธฐ?

ํŠœํ”Œ๋Š” ๊ฐ„๋‹จํ•œ ๋‘ ๊ฐœ์˜ ๋ฐ์ดํ„ฐ ๊ทธ๋ฃน์„ ๋‹ค๋ฃจ๋Š” ๋ฐ ๋งค์šฐ ์ ํ•ฉํ•ฉ๋‹ˆ๋‹ค.
๋” ๋ณต์žกํ•œ ๋ฐ์ดํ„ฐ ๊ตฌ์กฐ๊ฐ€ ํ•„์š”ํ•˜๋ฉด ํด๋ž˜์Šค๋‚˜ ๊ตฌ์กฐ์ฒด๋ฅผ ์‚ฌ์šฉํ•˜๋Š” ๊ฒƒ๋„ ์ข‹์€ ๋ฐฉ๋ฒ•์ž…๋‹ˆ๋‹ค.




๐Ÿ“”

๋Œ“๊ธ€๋‚จ๊ธฐ๊ธฐ