คลาส Tuple<T1,T2,T3,T4,T5,T6,T7> แสดงถึง 7-tuple เรียกว่า "Septet" Tuple เป็นโครงสร้างข้อมูลที่มีลำดับขององค์ประกอบ
การใช้งาน
- เข้าถึงชุดข้อมูลได้ง่ายขึ้น
- จัดการชุดข้อมูลได้ง่ายขึ้น
- แสดงชุดข้อมูลเดียว
- คืนค่าหลายค่าจากเมธอด
- ส่งค่าหลายค่าไปยังเมธอด
คุณสมบัติ 7 ตัว
- Item1 — คอมโพเนนต์ที่ 1
- Item2 — คอมโพเนนต์ที่ 2
- Item3 — คอมโพเนนต์ที่ 3
- Item4 — คอมโพเนนต์ที่ 4
- Item5 — คอมโพเนนต์ที่ 5
- Item6 — คอมโพเนนต์ที่ 6
- Item7 — คอมโพเนนต์ที่ 7
ตัวอย่างที่ 1: ตรวจสอบค่าต่างๆ
using System;
public class Demo
{
public static void Main(string[] args)
{
Tuple<int, int, int, int, int, int, int> tuple = new Tuple<int, int, int, int, int, int, int>(100, 150, 200, 300, 600, 1000, 2000);
Console.WriteLine("Value (Item1)= " + tuple.Item1);
Console.WriteLine("Value (Item2)= " + tuple.Item2);
Console.WriteLine("Value (Item3)= " + tuple.Item3);
Console.WriteLine("Value (Item4)= " + tuple.Item4);
Console.WriteLine("Value (Item5)= " + tuple.Item5);
Console.WriteLine("Value (Item6)= " + tuple.Item6);
Console.WriteLine("Value (Item7)= " + tuple.Item7);
if (tuple.Item5 == 600)
Console.WriteLine("Exists: Tuple Item 5 = " + tuple.Item5);
if (tuple.Item6 == 900)
Console.WriteLine("Exists: Tuple Item 6 = " + tuple.Item6);
if (tuple.Item7 == 2000)
Console.WriteLine("Exists: Tuple Item 7 = " + tuple.Item7);
}
}
ผลลัพธ์
Value (Item1)= 100
Value (Item2)= 150
Value (Item3)= 200
Value (Item4)= 300
Value (Item5)= 600
Value (Item6)= 1000
Value (Item7)= 2000
Exists: Tuple Item 5 = 600
Exists: Tuple Item 7 = 2000
ตัวอย่างที่ 2: Item6 และ Item7 เท่ากัน
using System;
public class Demo
{
public static void Main(string[] args)
{
Tuple<int, int, int, int, int, int, int> tuple = new Tuple<int, int, int, int, int, int, int>(100, 150, 200, 300, 600, 1000, 1000);
Console.WriteLine("Value (Item1)= " + tuple.Item1);
Console.WriteLine("Value (Item2)= " + tuple.Item2);
Console.WriteLine("Value (Item3)= " + tuple.Item3);
Console.WriteLine("Value (Item4)= " + tuple.Item4);
Console.WriteLine("Value (Item5)= " + tuple.Item5);
Console.WriteLine("Value (Item6)= " + tuple.Item6);
Console.WriteLine("Value (Item7)= " + tuple.Item7);
if (tuple.Item5 == 600)
Console.WriteLine("Exists: Tuple Item 5 = " + tuple.Item5);
if (tuple.Item6 == 900)
Console.WriteLine("Exists: Tuple Item 6 = " + tuple.Item6);
if (tuple.Item7 == 2000)
Console.WriteLine("Exists: Tuple Item 7 = " + tuple.Item7);
if (tuple.Item7 == tuple.Item6)
Console.WriteLine("Tuple Items Matched!");
}
}
ผลลัพธ์
Value (Item1)= 100
Value (Item2)= 150
Value (Item3)= 200
Value (Item4)= 300
Value (Item5)= 600
Value (Item6)= 1000
Value (Item7)= 1000
Exists: Tuple Item 5 = 600
Tuple Items Matched!
ข้อจำกัด: Tuple รองรับสูงสุด 8 คอมโพเนนต์ (Tuple<T1...T8>.) สำหรับมากกว่านั้น ให้ใช้ Nested Tuple หรือ ValueTuple