C# | StringComparer.Compare Method
Last Updated :
30 Jun, 2019
StringComparer.Compare Method is used to compare two objects or strings and returns an indication of their relative sort order. There are 2 methods in the overload list of this method:
- Compare(Object, Object)
- Compare(String, String)
Compare(Object, Object)
This method compares two objects and returns an indication of their relative sort order when overridden in a derived class.
Syntax:
public int Compare (object a, object b);
Here, a is the 1st object and b is the 2nd object to be compared with each other.
Returns: This method returns a signed integer that indicates the relative values of the object a and b. The values are returned according to the following table:
Value |
Meaning |
Less than zero |
a precedes b in the sort order or a is null and b is not null. |
Zero |
a is equal to b or a and b are both null. |
Greater than zero |
a follows b in the sort order or b is null and a is not null. |
Exception: This method will give ArgumentException if neither a nor b is a String object, and neither a nor b implements the IComparable interface.
Example:
using System;
using System.Collections;
class gfg {
public class cmp : IComparer {
int IComparer.Compare(Object x, Object y)
{
return (( new CaseInsensitiveComparer()).Compare(x, y));
}
}
public static void Main()
{
string [] arr = { "A" , "E" , "D" , "C" , "B" };
Console.WriteLine( "Original array:" );
print(arr);
Array.Sort(arr);
Console.WriteLine( "Sort using sort function:" );
print(arr);
Array.Sort(arr, new cmp());
Console.WriteLine( "Sorting using compare method :" );
print(arr);
}
public static void print(IEnumerable list)
{
foreach ( var v in list)
Console.WriteLine(v);
Console.WriteLine();
}
}
|
Output:
Original array:
A
E
D
C
B
Sort using sort function:
A
B
C
D
E
Sorting using compare method :
A
B
C
D
E
Compare(String, String)
This method compares two strings and returns an indication of their relative sort order when overridden in a derived class.
Syntax:
public abstract int Compare (string a, string b);
Here, a is the 1st string and b is the 2nd string to be compared with each other.
Returns: This method returns a signed integer that indicates the relative values of the object a and b. The values are returned according to the following table:
Value |
Meaning |
Less than zero |
a precedes b in the sort order or a is null and b is not null. |
Zero |
a is equal to b or a and b are both null. |
Greater than zero |
a follows b in the sort order or b is null and a is not null. |
Exception: This method will give ArgumentException if neither a nor b is a String object, and neither a nor b implements the IComparable interface.
Example:
using System;
using System.Collections.Generic;
class GFG {
static void Main( string [] args)
{
string s1 = "geek" ;
string s2 = "Geek" ;
int st = 0;
st = string .Compare(s1, s2);
Console.WriteLine(st.ToString());
}
}
|
Reference:
Share your thoughts in the comments
Please Login to comment...