CompareInfo.Compare Method (String, String)

July 28, 2014

Compares two strings and returns an integer that indicates their relationship to one another in the sort order.

Namespace:  System.Globalization
Assembly:  mscorlib (in mscorlib.dll)

public virtual int Compare(
	string string1,
	string string2
)

Parameters

string1
Type: System.String
The first string to compare.
string2
Type: System.String
The second string to compare.

Return Value

Type: System.Int32
An integer that indicates the relationship between the two strings in the sort order, as follows:

Value

Condition

zero

The two strings are equal.

less than zero

string1 precedes string2.

greater than zero

string1 follows string2.

By default, the comparison is performed using CompareOptions.None. To explicitly define the options used in the comparison, call the CompareInfo.Compare overload.

The following example demonstrates calling the Compare method.


using System;
using System.Text;
using System.Globalization;

public sealed class Example
{
   public static void Demo(System.Windows.Controls.TextBlock outputBlock)
   {
      String[] sign = new String[] { "<", "=", ">" };

      // The code below demonstrates how strings compare 
      // differently for different cultures.
      String s1 = "Coté", s2 = "coté", s3 = "côte";

      // Set sort order of strings for French in France.
      CompareInfo ci = new CultureInfo("fr-FR").CompareInfo;

      // Display the result using fr-FR Compare of Coté = coté.  	
      outputBlock.Text += String.Format("fr-FR Compare: {0} {2} {1}",
          s1, s2, sign[ci.Compare(s1, s2, CompareOptions.IgnoreCase) + 1]);

      // Display the result using fr-FR Compare of coté > côte.
      outputBlock.Text += String.Format("fr-FR Compare: {0} {2} {1}",
          s2, s3, sign[ci.Compare(s2, s3, CompareOptions.None) + 1]);

      // Set sort order of strings for Japanese as spoken in Japan.
      ci = new CultureInfo("ja-JP").CompareInfo;

      // Display the result using ja-JP Compare of coté < côte. 
      outputBlock.Text += String.Format("ja-JP Compare: {0} {2} {1}",
          s2, s3, sign[ci.Compare(s2, s3) + 1]);
   }
}

// This code produces the following output.
// 
// fr-FR Compare: Coté = coté
// fr-FR Compare: coté > côte
// ja-JP Compare: coté < côte


Windows Phone OS

Supported in: 8.1, 8.0, 7.1, 7.0

Windows Phone

Show:
© 2014 Microsoft