BigInteger.CompareTo Método

Definición

Compara el valor de esta instancia con otro valor y devuelve un entero que indica si el valor de esta instancia es menor, igual o mayor que el otro valor.

Sobrecargas

CompareTo(Int64)

Compara esta instancia con un entero de 64 bits con signo y devuelve un entero que indica si el valor de esta instancia es menor, igual o mayor que el valor del entero de 64 bits con signo.

CompareTo(BigInteger)

Compara esta instancia con un segundo BigInteger y devuelve un entero que indica si el valor de esta instancia es menor, igual o mayor que el valor del objeto especificado.

CompareTo(Object)

Compara esta instancia con un objeto especificado y devuelve un entero que indica si el valor de esta instancia es mayor, igual o menor que el valor del objeto especificado.

CompareTo(UInt64)

Compara esta instancia con un entero de 64 bits sin signo y devuelve un entero que indica si el valor de esta instancia es menor, igual o mayor que el valor del entero de 64 bits sin signo.

CompareTo(Int64)

Source:
BigInteger.cs
Source:
BigInteger.cs
Source:
BigInteger.cs

Compara esta instancia con un entero de 64 bits con signo y devuelve un entero que indica si el valor de esta instancia es menor, igual o mayor que el valor del entero de 64 bits con signo.

public:
 int CompareTo(long other);
public int CompareTo (long other);
member this.CompareTo : int64 -> int
Public Function CompareTo (other As Long) As Integer

Parámetros

other
Int64

Entero de 64 bits con signo que se va a comparar.

Devoluciones

Valor entero con signo que indica la relación de esta instancia con other, como se muestra en la tabla siguiente.

Valor devuelto Descripción
Menor que cero La instancia actual es menor que other.
Cero La instancia actual es igual que other.
Mayor que cero La instancia actual es mayor que other.

Ejemplos

En el ejemplo siguiente se muestra el resultado de llamar al CompareTo(Int64) método con valores enteros.

BigInteger bigIntValue = BigInteger.Parse("3221123045552");

byte byteValue = 16;
sbyte sbyteValue = -16;
short shortValue = 1233;
ushort ushortValue = 1233;
int intValue = -12233;
uint uintValue = 12233;
long longValue = 12382222;
ulong ulongValue = 1238222;

Console.WriteLine("Comparing {0} with {1}: {2}",
                  bigIntValue, byteValue,
                  bigIntValue.CompareTo(byteValue));
Console.WriteLine("Comparing {0} with {1}: {2}",
                  bigIntValue, sbyteValue,
                  bigIntValue.CompareTo(sbyteValue));
Console.WriteLine("Comparing {0} with {1}: {2}",
                  bigIntValue, shortValue,
                  bigIntValue.CompareTo(shortValue));
Console.WriteLine("Comparing {0} with {1}: {2}",
                  bigIntValue, ushortValue,
                  bigIntValue.CompareTo(ushortValue));
Console.WriteLine("Comparing {0} with {1}: {2}",
                  bigIntValue, intValue,
                  bigIntValue.CompareTo(intValue));
Console.WriteLine("Comparing {0} with {1}: {2}",
                  bigIntValue, uintValue,
                  bigIntValue.CompareTo(uintValue));
Console.WriteLine("Comparing {0} with {1}: {2}",
                  bigIntValue, longValue,
                  bigIntValue.CompareTo(longValue));
Console.WriteLine("Comparing {0} with {1}: {2}",
                  bigIntValue, ulongValue,
                  bigIntValue.CompareTo(ulongValue));
// The example displays the following output:
//       Comparing 3221123045552 with 16: 1
//       Comparing 3221123045552 with -16: 1
//       Comparing 3221123045552 with 1233: 1
//       Comparing 3221123045552 with 1233: 1
//       Comparing 3221123045552 with -12233: 1
//       Comparing 3221123045552 with 12233: 1
//       Comparing 3221123045552 with 12382222: 1
//       Comparing 3221123045552 with 1238222: 1
Dim bigIntValue As BigInteger = BigInteger.Parse("3221123045552")

Dim byteValue As Byte = 16
Dim sbyteValue As SByte = -16
Dim shortValue As Short = 1233      
Dim ushortValue As UShort = 1233
Dim intValue As Integer = -12233
Dim uintValue As UInteger = 12233
Dim longValue As Long = 12382222
Dim ulongValue As Integer = 1238222

Console.WriteLine("Comparing {0} with {1}: {2}", _
                  bigIntValue, byteValue, _
                  bigIntValue.CompareTo(byteValue))
Console.WriteLine("Comparing {0} with {1}: {2}", _
                  bigIntValue, sbyteValue, _
                  bigIntValue.CompareTo(sbyteValue)) 
Console.WriteLine("Comparing {0} with {1}: {2}", _
                  bigIntValue, shortValue, _
                  bigIntValue.CompareTo(shortValue)) 
Console.WriteLine("Comparing {0} with {1}: {2}", _
                  bigIntValue, ushortValue, _
                  bigIntValue.CompareTo(ushortValue)) 
Console.WriteLine("Comparing {0} with {1}: {2}", _
                  bigIntValue, intValue, _
                  bigIntValue.CompareTo(intValue)) 
Console.WriteLine("Comparing {0} with {1}: {2}", _
                  bigIntValue, uintValue, _
                  bigIntValue.CompareTo(uintValue)) 
Console.WriteLine("Comparing {0} with {1}: {2}", _
                  bigIntValue, longValue, _
                  bigIntValue.CompareTo(longValue)) 
Console.WriteLine("Comparing {0} with {1}: {2}", _
                  bigIntValue, ulongValue, _
                  bigIntValue.CompareTo(ulongValue))
' The example displays the following output:
'       Comparing 3221123045552 with 16: 1
'       Comparing 3221123045552 with -16: 1
'       Comparing 3221123045552 with 1233: 1
'       Comparing 3221123045552 with 1233: 1
'       Comparing 3221123045552 with -12233: 1
'       Comparing 3221123045552 with 12233: 1
'       Comparing 3221123045552 with 12382222: 1
'       Comparing 3221123045552 with 1238222: 1

Comentarios

Si other es un Bytevalor , , SByteInt16Int32, UInt16, o UInt32 , se convierte implícitamente en un Int64 valor cuando se llama al CompareTo(Int64) método .

Se aplica a

CompareTo(BigInteger)

Source:
BigInteger.cs
Source:
BigInteger.cs
Source:
BigInteger.cs

Compara esta instancia con un segundo BigInteger y devuelve un entero que indica si el valor de esta instancia es menor, igual o mayor que el valor del objeto especificado.

public:
 virtual int CompareTo(System::Numerics::BigInteger other);
public int CompareTo (System.Numerics.BigInteger other);
abstract member CompareTo : System.Numerics.BigInteger -> int
override this.CompareTo : System.Numerics.BigInteger -> int
Public Function CompareTo (other As BigInteger) As Integer

Parámetros

other
BigInteger

Objeto que se va a comparar.

Devoluciones

Valor entero con signo que indica la relación de esta instancia con other, como se muestra en la tabla siguiente.

Valor devuelto Descripción
Menor que cero La instancia actual es menor que other.
Cero La instancia actual es igual que other.
Mayor que cero La instancia actual es mayor que other.

Implementaciones

Ejemplos

En el ejemplo siguiente se muestra el uso del CompareTo(BigInteger) método para ordenar una lista de StarInfo objetos. Cada StarInfo objeto proporciona información sobre el nombre de una estrella y su distancia desde la Tierra en millas. StarInfo implementa la IComparable<T> interfaz , que permite StarInfo ordenar los objetos por clases de colección genéricas. Su IComparable<T>.CompareTo implementación solo ajusta una llamada a CompareTo(BigInteger).

using System;
using System.Collections.Generic;
using System.Numerics;

public struct StarInfo : IComparable<StarInfo>
{
   // Define constructors.
   public StarInfo(string name, double lightYears)
   {
      this.Name = name;

      // Calculate distance in miles from light years.
      this.Distance = (BigInteger) Math.Round(lightYears * 5.88e12);
   }

   public StarInfo(string name, BigInteger distance)
   {
      this.Name = name;
      this.Distance = distance;
   }

   // Define public fields.
   public string Name;
   public BigInteger Distance;

   // Display name of star and its distance in parentheses.
   public override string ToString()
   {
      return String.Format("{0,-10} ({1:N0})", this.Name, this.Distance);
   }

   // Compare StarInfo objects by their distance from Earth.
   public int CompareTo(StarInfo other)
   {
      return this.Distance.CompareTo(other.Distance);
   }
}
Imports System.Collections.Generic
Imports System.Numerics

Public Structure StarInfo : Implements IComparable(Of StarInfo)
   ' Define constructors.
   Public Sub New(name As String, lightYears As Double)
      Me.Name = name
      ' Calculate distance in miles from light years.
      Me.Distance = CType(Math.Round(lightYears * 5.88e12), BigInteger)
   End Sub
   
   Public Sub New(name As String, distance As BigInteger)
      Me.Name = name
      Me.Distance = distance
   End Sub
   
   ' Define public fields.
   Public Name As String
   Public Distance As BigInteger

   ' Display name of star and its distance in parentheses.
   Public Overrides Function ToString() As String
      Return String.Format("{0,-10} ({1:N0})", Me.Name, Me.Distance)
   End Function

   ' Compare StarInfo objects by their distance from Earth.
   Public Function CompareTo(other As starInfo) As Integer _
                   Implements IComparable(Of StarInfo).CompareTo
      Return Me.Distance.CompareTo(other.Distance)
   End Function                
End Structure

A continuación, el código siguiente crea una instancia de cuatro StarInfo objetos y los almacena en un objeto genérico List<T> . Después de llamar al List<T>.Sort método , StarInfo los objetos se muestran en orden de su distancia desde la Tierra.

public class Example
{
   public static void Main()
   {
      StarInfo star;
      List<StarInfo> stars = new List<StarInfo>();

      star = new StarInfo("Sirius", 8.6d);
      stars.Add(star);
      star = new StarInfo("Rigel", 1400d);
      stars.Add(star);
      star = new StarInfo("Castor", 49d);
      stars.Add(star);
      star = new StarInfo("Antares", 520d);
      stars.Add(star);

      stars.Sort();

      foreach (StarInfo sortedStar in stars)
         Console.WriteLine(sortedStar);
   }
}
// The example displays the following output:
//       Sirius     (50,568,000,000,000)
//       Castor     (288,120,000,000,000)
//       Antares    (3,057,600,000,000,000)
//       Rigel      (8,232,000,000,000,000)
Module Example
   Public Sub Main()
      Dim star As StarInfo
      Dim stars As New List(Of StarInfo)
      
      star = New StarInfo("Sirius", 8.6d)
      stars.Add(star)
      star = New StarInfo("Rigel", 1400d)
      stars.Add(star)
      star = New StarInfo("Castor", 49d)
      stars.Add(star)
      star = New StarInfo("Antares", 520d)
      stars.Add(star)
      
      stars.Sort()
      
      For Each star In stars
         Console.WriteLine(star)
      Next   
   End Sub
End Module
' The example displays the following output:
'       Sirius     (50,568,000,000,000)
'       Castor     (288,120,000,000,000)
'       Antares    (3,057,600,000,000,000)
'       Rigel      (8,232,000,000,000,000)

Comentarios

Esta sobrecarga del CompareTo método implementa el IComparable<T>.CompareTo método . Los objetos de colección genéricos lo usan para ordenar los elementos de la colección.

Consulte también

Se aplica a

CompareTo(Object)

Source:
BigInteger.cs
Source:
BigInteger.cs
Source:
BigInteger.cs

Compara esta instancia con un objeto especificado y devuelve un entero que indica si el valor de esta instancia es mayor, igual o menor que el valor del objeto especificado.

public:
 virtual int CompareTo(System::Object ^ obj);
public int CompareTo (object? obj);
public int CompareTo (object obj);
abstract member CompareTo : obj -> int
override this.CompareTo : obj -> int
Public Function CompareTo (obj As Object) As Integer

Parámetros

obj
Object

Objeto que se va a comparar.

Devoluciones

Entero con signo que indica la relación de la instancia actual con el parámetro obj, como se muestra en la tabla siguiente.

Valor devuelto Descripción
Menor que cero La instancia actual es menor que obj.
Cero La instancia actual es igual que obj.
Mayor que cero La instancia actual es mayor que obj o el parámetro obj es null.

Implementaciones

Excepciones

Ejemplos

En el ejemplo siguiente se llama al CompareTo(Object) método para comparar un BigInteger valor con cada elemento de una matriz de objetos:

object[] values = { BigInteger.Pow(Int64.MaxValue, 10), null,
                    12.534, Int64.MaxValue, BigInteger.One };
BigInteger number = UInt64.MaxValue;

foreach (object value in values)
{
   try {
      Console.WriteLine("Comparing {0} with '{1}': {2}", number, value,
                        number.CompareTo(value));
   }
   catch (ArgumentException) {
      Console.WriteLine("Unable to compare the {0} value {1} with a BigInteger.",
                        value.GetType().Name, value);
   }
}
// The example displays the following output:
//    Comparing 18446744073709551615 with '4.4555084156466750133735972424E+189': -1
//    Comparing 18446744073709551615 with '': 1
//    Unable to compare the Double value 12.534 with a BigInteger.
//    Unable to compare the Int64 value 9223372036854775807 with a BigInteger.
//    Comparing 18446744073709551615 with '1': 1
Dim values() As Object = { BigInteger.Pow(Int64.MaxValue, 10), Nothing, 
                           12.534, Int64.MaxValue, BigInteger.One }
Dim number As BigInteger = UInt64.MaxValue

For Each value As Object In values
   Try
      Console.WriteLine("Comparing {0} with '{1}': {2}", number, value, 
                        number.CompareTo(value))
   Catch e As ArgumentException
      Console.WriteLine("Unable to compare the {0} value {1} with a BigInteger.",
                        value.GetType().Name, value)
   End Try                     
Next                                 
' The example displays the following output:
'    Comparing 18446744073709551615 with '4.4555084156466750133735972424E+189': -1
'    Comparing 18446744073709551615 with '': 1
'    Unable to compare the Double value 12.534 with a BigInteger.
'    Unable to compare the Int64 value 9223372036854775807 with a BigInteger.
'    Comparing 18446744073709551615 with '1': 1

Comentarios

Esta sobrecarga del CompareTo método implementa el IComparable.CompareTo método . Los objetos de colección no genéricos usan para ordenar los elementos de la colección.

El obj parámetro debe ser uno de los siguientes:

  • Objeto cuyo tipo de tiempo de ejecución es BigInteger.

  • Variable Object cuyo valor es null. Si el valor del obj parámetro es null, el método devuelve 1, lo que indica que la instancia actual es mayor que obj.

Consulte también

Se aplica a

CompareTo(UInt64)

Source:
BigInteger.cs
Source:
BigInteger.cs
Source:
BigInteger.cs

Importante

Esta API no es conforme a CLS.

Compara esta instancia con un entero de 64 bits sin signo y devuelve un entero que indica si el valor de esta instancia es menor, igual o mayor que el valor del entero de 64 bits sin signo.

public:
 int CompareTo(System::UInt64 other);
[System.CLSCompliant(false)]
public int CompareTo (ulong other);
[<System.CLSCompliant(false)>]
member this.CompareTo : uint64 -> int
Public Function CompareTo (other As ULong) As Integer

Parámetros

other
UInt64

Entero de 64 bits sin signo que se va a comparar.

Devoluciones

Entero con signo que indica el valor relativo de esta instancia y other, como se muestra en la tabla siguiente.

Valor devueltoDescripción
Menor que ceroLa instancia actual es menor que other.
CeroLa instancia actual es igual que other.
Mayor que ceroLa instancia actual es mayor que other.
Atributos

Se aplica a