Posted by: Cirilo Meggiolaro | 03/17/2009

Tip of the day #154 – SortKey class

Thanks to the .NET Framework create multi-language applications is not a matter for headaches. The System.Globalization namespace has a full set of features to help you out all along your needs.

Let’s check today the SortKey class that stores information about how a string will be compared such as culture-specific sorting rules, the bytes that encode the string and user-specific compare options.

Main properties and methods

  • virtual byte[] KeyData: Read-only property that retrieves an array of bytes representing the SortKey object;
  • virtual string OriginalString: Read-only property that retrieves the original string used to create the SortKey object;
  • static int Compare(SortKey sortkey1, SortKey sortkey2): Method that compares two sort keys and returns an integer number that represents the sort weight on both sort key objects. A value of -1 means that the sortkey1 object is less than sortkey2. A value of zero means that both have the same weight while a value of mean means that the sortkey1 has a greater weight than the sortkey2.

How to…

The following example demonstrates two comparisons between en-US and es-ES cultures. The difference between each comparison is that on the first one the code uses an international sort settings and the second one creates an es-ES culture using traditional sort.

/// Base string to be compared.
string baseText = “choice”;

/// Creates a compare info object based on the English (United States) culture.
CompareInfo compareUS = new CultureInfo(“en-US”, false).CompareInfo;
SortKey sortkeyIntUS = compareUS.GetSortKey(baseText);

/// Creates a compare info object based on the
/// Spanish (Spain) culture using international sort.
CompareInfo compareES = new CultureInfo(“es-ES”, false).CompareInfo;
SortKey sortkeyIntES = compareES.GetSortKey(baseText);

/// Creates a compare info object based on the
/// Spanish (Spain) culture using traditional sort.

CompareInfo compareTradES = new CultureInfo(0x040A, false).CompareInfo;
SortKey sortkeyTradES = compareTradES.GetSortKey(baseText);

/// Using international sort both strings have the same sort weight.
Console.WriteLine(“Compare result with international sort: {0}”, SortKey.Compare(sortkeyIntUS, sortkeyIntES));

/// Using traditional sort on the spanish culture makes
/// the english version to have a greater weight.
Console.WriteLine(“Compare result with traditional sort: {0}”, SortKey.Compare(sortkeyIntUS, sortkeyTradES));


Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )


Connecting to %s


%d bloggers like this: