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

วิธีสร้าง 2-tuple หรือ pair tuple ใน C#

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

ตัวอย่าง

ตัวอย่างที่ 1: สร้าง tuple ของสตริงสองค่า

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

ผลลัพธ์

Value = jack 
Exists: Tuple Value = jack

ตัวอย่างเพิ่มเติม

ตัวอย่างที่ 2: สร้าง tuple ของ int และ string

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

ผลลัพธ์

Value = 20 
Exists: Tuple Value = 20