Computer >> Hướng Dẫn Máy Tính >  >> Lập Trình >> C#

Lớp Tuple<T1,T2,T3,T4> trong C#

Lớp Tuple<T1,T2,T3,T4> biểu diễn 4-tuple, còn gọi là quadruple (bộ bốn). Tuple là cấu trúc dữ liệu có trình tự các phần tử.

Tuple được dùng để:

  • Truy cập tập dữ liệu dễ dàng hơn.
  • Thao tác tập dữ liệu dễ dàng hơn.
  • Biểu diễn một tập dữ liệu đơn lẻ.
  • Trả về nhiều giá trị từ phương thức.
  • Truyền nhiều giá trị cho phương thức.

Có 4 thuộc tính:

  • Item1 - Giá trị thành phần đầu tiên.
  • Item2 - Giá trị thành phần thứ hai.
  • Item3 - Giá trị thành phần thứ ba.
  • Item4 - Giá trị thành phần thứ tư.

Ví dụ 1

using System;
public class Demo
{
    public static void Main(string[] args)
    {
        Tuple tuple = new Tuple("nathan", "steve", "katie", "tim");
        Console.WriteLine("Value (Item1)= " + tuple.Item1);
        Console.WriteLine("Value (Item2)= " + tuple.Item2);
        Console.WriteLine("Value (Item3)= " + tuple.Item3);
        Console.WriteLine("Value (Item4)= " + tuple.Item4);
        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);
        }
        if (tuple.Item4 == "tom")
        {
            Console.WriteLine("Exists: Tuple Value = " + tuple.Item4);
        }
    }
}

Đầu ra

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

Ví dụ 2

using System;
public class Demo
{
    public static void Main(string[] args)
    {
        Tuple tuple = new Tuple(100, 150, 300, 450);
        Console.WriteLine("Value (Item1)= " + tuple.Item1);
        Console.WriteLine("Value (Item2)= " + tuple.Item2);
        Console.WriteLine("Value (Item3)= " + tuple.Item3);
        Console.WriteLine("Value (Item4)= " + tuple.Item4);
        if (tuple.Item1 == 100)
        {
            Console.WriteLine("Exists: Tuple Item 1 = " + tuple.Item1);
        }
        if (tuple.Item2 == 250)
        {
            Console.WriteLine("Exists: Tuple Item 2 = " + tuple.Item2);
        }
        if (tuple.Item3 == 270)
        {
            Console.WriteLine("Exists: Tuple Item 3 = " + tuple.Item3);
        }
        if (tuple.Item4 == 300)
        {
            Console.WriteLine("Exists: Tuple Item 4 = " + tuple.Item4);
        }
    }
}

Đầu ra

Value (Item1)= 100
Value (Item2)= 150
Value (Item3)= 300
Value (Item4)= 450
Exists: Tuple Item 1 = 100