Open In App

Comparing two ValueTuple<T1, T2, T3, T4, T5, T6, T7, TRest> in C#

ValueTuple is a structure introduced in C# 7.0 which represents the value type Tuple. It is already included in .NET Framework 4.7 or higher version. It allows you to store a data set that contains multiple values that may or may not be related to each other.
You can also compare the instance of two value tuples with each other by using CompareTo(ValueTuple<T1, T2, T3, T4, T5, T6, T7, TRest>) method. Or in other words, with the help of CompareTo method you are allowed to compare the current ValueTuple<T1, T2, T3, T4, T5, T6, T7, TRest> instance to a specified ValueTuple<T1, T2, T3, T4, T5, T6, T7, TRest> instance. This method also compares nested value tuples with each other.

Syntax:



public int CompareTo (ValueTuple other);

Return Type: The return type of this method is System.Int32. And it always returns a signed integer that indicates the relative position of this instance and other in the sort order as shown in the below list:

Example 1:




// C# program to illustrate the 
// use of CompareTo method
using System;
  
namespace exampleofvaluetuple {
  
class GFG {
  
    // Main Method
    static void Main(string[] args)
    {
        // 8-ValueTuple
        var t1 = ValueTuple.Create(43, 34, 22, 7, 8,
                29, 30, ValueTuple.Create(1, 2, 3));
  
        var t2 = ValueTuple.Create(78, 98, 76, 67, 54,
               78, 89, ValueTuple.Create(10, 22, 30));
  
        Console.WriteLine("Result 1: {0}", t1.CompareTo(t2));
  
        // 8-ValueTuple
        var p1 = ValueTuple.Create(86, 99, 67, 88, 89,
               96, 78, ValueTuple.Create(90, 80, 70));
  
        var p2 = ValueTuple.Create(44, 22, 06, 55, 12, 
                  16, 23, ValueTuple.Create(9, 8, 7));
  
        Console.WriteLine("Result 2: {0}", p1.CompareTo(p2));
  
        // 8-ValueTuple
        var q1 = ValueTuple.Create(10, 20, 30, 40, 50,
               60, 70, ValueTuple.Create(22, 33, 44));
  
        var q2 = ValueTuple.Create(10, 20, 30, 40, 50,
               60, 70, ValueTuple.Create(22, 33, 44));
  
        Console.WriteLine("Result 3: {0}", q1.CompareTo(q2));
    }
}
}

Output:

Result 1: -1
Result 2: 1
Result 3: 0

Example 2:




// C# program to illustrate the
// use of CompareTo method
using System;
  
namespace exampleofvaluetuple {
  
class GFG {
  
    // Main Method
    static void Main(string[] args)
    {
        // 8-ValueTuple
        var t1 = ValueTuple.Create(44, 55, 66, 77, 88,
                  99, 33, ValueTuple.Create(1, 2, 3));
  
        var t2 = ValueTuple.Create(44, 55, 66, 77, 88, 
                  99, 33, ValueTuple.Create(1, 2, 3));
  
        // Using CompareTo Method
        if (t1.CompareTo(t2) == 0) {
  
            Console.WriteLine("Value tuples are equal!!");
        }
  
        else {
  
            Console.WriteLine("Value tuples are not equal!!");
        }
    }
}
}

Output:
Value tuples are equal!!

Article Tags :
C#