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

Duyệt Tuple trong C#

Tuple cũ (System.Tuple) truy cập qua Item1, Item2...

Tuple<int, string> tuple = new Tuple<int, string>(100, "Tom");

tuple.Item1; // 100
tuple.Item2; // "Tom"
Console.WriteLine(tuple); // (100, Tom)

Ví dụ

using System;
using System.Threading;

namespace Demo
{
    class Program
    {
        static void Main(string[] args)
        {
            Tuple<int, string> tuple = new Tuple<int, string>(100, "Tom");
            
            if (tuple.Item1 == 100) Console.WriteLine(tuple.Item1);
            if (tuple.Item2 == "Tom") Console.WriteLine(tuple.Item2);
            
            Console.WriteLine(tuple); // ToString() tự động
        }
    }
}

ValueTuple (C# 7+) - Khuyến nghị

// Cú pháp ngắn gọn
var tuple = (Id: 100, Name: "Tom");

// Truy cập bằng tên
Console.WriteLine(tuple.Id);   // 100
Console.WriteLine(tuple.Name); // Tom

// Deconstruction
var (id, name) = tuple;
Console.WriteLine($"{id}, {name}");

// Duyệt (cần reflection hoặc chuyển array)
var arr = new object[] { tuple.Id, tuple.Name };
foreach (var item in arr) Console.WriteLine(item);

Ưu điểm ValueTuple: Named elements, deconstruction, mutable, performance tốt hơn (struct), so sánh giá trị.