📜  如何在C#中比较两个ValueTuple?

📅  最后修改于: 2021-05-29 14:19:11             🧑  作者: Mango

要比较ValueTuple的两个实例,可以使用ValueTuple结构提供的CompareTo方法。 ValueTuple.CompareTo(ValueTuple)方法用于将ValueTuple的当前实例与另一个ValueTuple实例进行比较。如果它们彼此相等,则始终返回零。

句法:

public int CompareTo (ValueTuple other);

在这里,另一个是要与当前实例进行比较的对象。

返回:该方法始终返回System.Int32类型的0。

异常:如果另一个不是ValueTuple实例,则此方法将引发ArgumentException。

范例1:

// C# program to illustrate the 
// concept of CompareTo method
using System;
  
class GFG {
  
    // Main method
    static public void Main()
    {
  
        // Creating value tuples with two elements
        var MyTple1 = ValueTuple.Create(56, 45);
        var MyTple2 = ValueTuple.Create(56, 3);
        var MyTple3 = ValueTuple.Create(56, 45);
        var MyTple4 = ValueTuple.Create(5345, 45);
  
        // Using CompareTo method
        int res1 = MyTple1.CompareTo(MyTple2);
        int res2 = MyTple1.CompareTo(MyTple3);
        int res3 = MyTple1.CompareTo(MyTple4);
  
        // Display result
        Console.WriteLine("Result 1: " + res1);
        Console.WriteLine("Result 2: " + res2);
        Console.WriteLine("Result 3: " + res3);
    }
}
输出:
Result 1: 1
Result 2: 0
Result 3: -1

范例2:

// C# program to illustrate the
// use of CompareTo method
using System;
  
class GFG {
  
    // Main Method
    static public void Main()
    {
  
        // Creating value tuples with one element
        var MyVTple1 = ValueTuple.Create(2018);
        var MyVTple2 = ValueTuple.Create(2018);
  
        // Compare both value tuples
        // Using CompareTo method
        if (MyVTple1.CompareTo(MyVTple2) == 0) 
        {
            Console.WriteLine("Welcome to GeeksforGeeks");
        }
  
        else 
        {
            Console.WriteLine("Page Not Found");
        }
    }
}
输出:
Welcome to GeeksforGeeks

参考:

  • https://docs.microsoft.com/zh-cn/dotnet/api/system.valuetuple.compareto?view=netframework-4.8