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

Tuple lồng nhau (Nested Tuples) trong C#

Tuple trong C# có thể lồng nhau để biểu diễn cấu trúc dữ liệu phức tạp hơn 8 phần tử (giới hạn của Tuple<T1..T8>). Phần tử thứ 8 (Item8/Rest) thường được dùng để chứa tuple lồng.

Khai báo Nested Tuple

var tuple = Tuple.Create(
    100, 200, 300, 400, 500, 600,
    Tuple.Create(720, 750, 780),  // Nested tuple ở vị trí 7
    800
);

Truy cập phần tử lồng

// Phần tử 1-6
tuple.Item1;  // 100
tuple.Item6;  // 600

// Phần tử lồng (thứ 7)
tuple.Item7.Item1;  // 720
tuple.Item7.Item2;  // 750
tuple.Item7.Item3;  // 780

// Phần tử 8 (Rest)
tuple.Rest.Item1;   // 800

Mã nguồn hoàn chỉnh

using System;

public class Program
{
    public static void Main()
    {
        var tuple = Tuple.Create(100, 200, 300, 400, 500, 600,
            Tuple.Create(720, 750, 780), 800);
        
        Console.WriteLine(tuple.Item1);  // 100
        Console.WriteLine(tuple.Item2);  // 200
        Console.WriteLine(tuple.Item3);  // 300
        Console.WriteLine(tuple.Item4);  // 400
        Console.WriteLine(tuple.Item5);  // 500
        Console.WriteLine(tuple.Item6);  // 600
        
        Console.WriteLine("\nNested Tuple...");
        Console.WriteLine(tuple.Item7.Item1);  // 720
        Console.WriteLine(tuple.Item7.Item2);  // 750
        Console.WriteLine(tuple.Item7.Item3);  // 780
        
        Console.WriteLine("\n8th element...\n" + tuple.Rest.Item1);  // 800
    }
}

Kết quả

100
200
300
400
500
600

Nested Tuple...
720
750
780

8th element...
800

Cách hiện đại: ValueTuple (C# 7+)

// ValueTuple hỗ trợ lồng tự nhiên, không giới hạn 8 phần tử
var modern = (1, 2, 3, 4, 5, 6, (7, 8, 9), 10);
Console.WriteLine(modern.Item7.Item2);  // 8
Console.WriteLine(modern.Rest.Item1);   // 10 (nếu dùng Tuple class)

// Deconstruction lồng
var (a, b, c, d, e, f, (g, h, i), j) = modern;

Lưu ý

  • Tuple class (legacy) giới hạn 8 phần tử, dùng Rest để truy cập phần tử 8+.
  • ValueTuple không có giới hạn, hỗ trợ deconstruction lồng nhau tự nhiên.
  • Tuple class immutable, ValueTuple mutable.