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

คลาส Tuple<T1,T2,T3> ใน C#

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

การใช้งาน

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

คุณสมบัติ

  • Item1 — ค่าคอมโพเนนต์แรก
  • Item2 — ค่าคอมโพเนนต์ที่สอง
  • Item3 — ค่าคอมโพเนนต์ที่สาม

ตัวอย่างที่ 1: Tuple<int, string, string>

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: Tuple<string, string, 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

แนะนำ: ใช้ ValueTuple (C# 7.0+) เช่น (int, string, string) แทน เพื่อประสิทธิภาพและ Syntax ที่ดีกว่า