Computer >> บทช่วยสอนคอมพิวเตอร์ >  >> การเขียนโปรแกรม >> C#

วิธีสร้าง 3-Tuple หรือ Triple Tuple ใน C#

คลาส Tuple<T1, T2, T3> แสดงถึง 3-tuple ซึ่งเรียกว่า "Triple" (สามค่า) Tuple เป็นโครงสร้างข้อมูลที่มีลำดับขององค์ประกอบ

การใช้งาน Tuple

  • เข้าถึงชุดข้อมูลได้ง่ายขึ้น
  • จัดการชุดข้อมูลได้ง่ายขึ้น
  • แสดงชุดข้อมูลเดียว
  • คืนค่าหลายค่าจากเมธอด
  • ส่งค่าหลายค่าไปยังเมธอด

ตัวอย่างที่ 1: สร้าง 3-Tuple แบบพื้นฐาน

using System;

public class Demo
{
    public static void Main(string[] args)
    {
        Tuple<int, string, string> tuple = new Tuple<int, string, string>(35, "steve", "katie");
        
        Console.WriteLine("Value (Item1)= " + tuple.Item1);
        Console.WriteLine("Value (Item2)= " + tuple.Item2);
        Console.WriteLine("Value (Item3)= " + tuple.Item3);
        
        if (tuple.Item1 == 35)
        {
            Console.WriteLine("Exists: Tuple Value = " + tuple.Item1);
        }
        if (tuple.Item2 == "jack")
        {
            Console.WriteLine("Exists: Tuple Value = " + tuple.Item2);
        }
        if (tuple.Item3 == "katie")
        {
            Console.WriteLine("Exists: Tuple Value = " + tuple.Item3);
        }
    }
}

ผลลัพธ์

Value (Item1)= 35
Value (Item2)= steve
Value (Item3)= katie
Exists: Tuple Value = 35
Exists: Tuple Value = katie

ตัวอย่างที่ 2: 3-Tuple ด้วยข้อมูลประเภท String

using System;

public class Demo
{
    public static void Main(string[] args)
    {
        Tuple<string, string, string> tuple = new Tuple<string, string, string>("nathan", "steve", "katie");
        
        Console.WriteLine("Value (Item1)= " + tuple.Item1);
        Console.WriteLine("Value (Item2)= " + tuple.Item2);
        Console.WriteLine("Value (Item3)= " + tuple.Item3);
        
        if (tuple.Item1 == "nathan")
        {
            Console.WriteLine("Exists: Tuple Value = " + tuple.Item1);
        }
        if (tuple.Item2 == "jack")
        {
            Console.WriteLine("Exists: Tuple Value = " + tuple.Item2);
        }
        if (tuple.Item3 == "katie")
        {
            Console.WriteLine("Exists: Tuple Value = " + tuple.Item3);
        }
    }
}

ผลลัพธ์

Value (Item1)= nathan
Value (Item2)= steve
Value (Item3)= katie
Exists: Tuple Value = nathan
Exists: Tuple Value = katie

หมายเหตุ: ตั้งแต่ C# 7.0 เป็นต้นมา สามารถใช้ ValueTuple (เช่น (int, string, string)) ซึ่งสะดวกกว่าและมีประสิทธิภาพดีกว่า