SortKey 类

定义

表示将字符串映射到其排序关键字的映射结果。Represents the result of mapping a string to its sort key.

public ref class SortKey
[System.Runtime.InteropServices.ComVisible(true)]
[System.Serializable]
public class SortKey
type SortKey = class
Public Class SortKey
继承
SortKey
属性

示例

下面的示例使用“en-US”和“es-ES”区域性以及“en-US”和“es-ES”传统区域性比较字符串“llama”。The following example compares the string "llama" using the "en-US" and "es-ES" cultures, and the "en-US" and "es-ES" traditional cultures.

using namespace System;
using namespace System::Globalization;
int main()
{
   
   // Creates a SortKey using the en-US culture.
   CultureInfo^ MyCI = gcnew CultureInfo( "en-US",false );
   CompareInfo^ myComp_enUS = MyCI->CompareInfo;
   SortKey^ mySK1 = myComp_enUS->GetSortKey( "llama" );
   
   // Creates a SortKey using the es-ES culture with international sort.
   MyCI = gcnew CultureInfo( "es-ES",false );
   CompareInfo^ myComp_esES = MyCI->CompareInfo;
   SortKey^ mySK2 = myComp_esES->GetSortKey( "llama" );
   
   // Creates a SortKey using the es-ES culture with traditional sort.
   MyCI = gcnew CultureInfo( 0x040A,false );
   CompareInfo^ myComp_es = MyCI->CompareInfo;
   SortKey^ mySK3 = myComp_es->GetSortKey( "llama" );
   
   // Compares the en-US SortKey with each of the es-ES SortKey objects.
   Console::WriteLine( "Comparing \"llama\" in en-US and in es-ES with international sort : {0}", SortKey::Compare( mySK1, mySK2 ) );
   Console::WriteLine( "Comparing \"llama\" in en-US and in es-ES with traditional sort   : {0}", SortKey::Compare( mySK1, mySK3 ) );
}

/*
This code produces the following output.

Comparing S"llama" in en-US and in es-ES with international sort : 0
Comparing S"llama" in en-US and in es-ES with traditional sort   : -1
*/
using System;
using System.Globalization;

public class SamplesSortKey  {

   public static void Main()  {

      // Creates a SortKey using the en-US culture.
      CompareInfo myComp_enUS = new CultureInfo("en-US",false).CompareInfo;
      SortKey mySK1 = myComp_enUS.GetSortKey( "llama" );

      // Creates a SortKey using the es-ES culture with international sort.
      CompareInfo myComp_esES = new CultureInfo("es-ES",false).CompareInfo;
      SortKey mySK2 = myComp_esES.GetSortKey( "llama" );

      // Creates a SortKey using the es-ES culture with traditional sort.
      CompareInfo myComp_es   = new CultureInfo(0x040A,false).CompareInfo;
      SortKey mySK3 = myComp_es.GetSortKey( "llama" );

      // Compares the en-US SortKey with each of the es-ES SortKey objects.
      Console.WriteLine( "Comparing \"llama\" in en-US and in es-ES with international sort : {0}", SortKey.Compare( mySK1, mySK2 ) );
      Console.WriteLine( "Comparing \"llama\" in en-US and in es-ES with traditional sort   : {0}", SortKey.Compare( mySK1, mySK3 ) );

   }

}

/*
This code produces the following output.

Comparing "llama" in en-US and in es-ES with international sort : 0
Comparing "llama" in en-US and in es-ES with traditional sort   : -1
*/

Imports System.Globalization

Public Class SamplesSortKey

   Public Shared Sub Main()

      ' Creates a SortKey using the en-US culture.
      Dim myComp_enUS As CompareInfo = New CultureInfo("en-US", False).CompareInfo
      Dim mySK1 As SortKey = myComp_enUS.GetSortKey("llama")

      ' Creates a SortKey using the es-ES culture with international sort.
      Dim myComp_esES As CompareInfo = New CultureInfo("es-ES", False).CompareInfo
      Dim mySK2 As SortKey = myComp_esES.GetSortKey("llama")

      ' Creates a SortKey using the es-ES culture with traditional sort.
      Dim myComp_es As CompareInfo = New CultureInfo(&H40A, False).CompareInfo
      Dim mySK3 As SortKey = myComp_es.GetSortKey("llama")

      ' Compares the en-US SortKey with each of the es-ES SortKey objects.
      Console.WriteLine("Comparing ""llama"" in en-US and in es-ES with international sort : {0}", SortKey.Compare(mySK1, mySK2))
      Console.WriteLine("Comparing ""llama"" in en-US and in es-ES with traditional sort   : {0}", SortKey.Compare(mySK1, mySK3))

   End Sub

End Class


'This code produces the following output.
'
'Comparing "llama" in en-US and in es-ES with international sort : 0
'Comparing "llama" in en-US and in es-ES with traditional sort   : -1

下面的示例演示如何使用 SortKey 类提高完全依赖于排序和搜索大型数组的应用程序中的性能。The following example shows how you can use the SortKey class to improve performance in an application that relies extensively on sorting and searching a large array. 该示例创建无序的名称数组,此实例中有 13 个元素。The example creates an unordered array of names, which in this case has 13 elements. 然后它将每个名称的排序键存储在并行数组中,后者会将其传递到 Array.Sort(Array, Array) 方法。It then stores the sort key of each name in a parallel array, which it passes to the Array.Sort(Array, Array) method. 结果为已排序的数组。The result is a sorted array. 然后,该示例搜索三个字符串的数组。The example then searches the array for three strings. 对于每个搜索字符串,它调用 CompareInfo.GetSortKey(String, CompareOptions) 方法来检索字符串的排序键,然后调用 Array.FindIndex 方法来检索该排序键在排序键数组中的索引。For each search string, it calls the CompareInfo.GetSortKey(String, CompareOptions) method to retrieve the string's sort key, and then calls the Array.FindIndex method to retrieve the index of that sort key in the array of sort keys. 由于名称和排序键数组是并行的,因此返回的索引也是 names 数组中的名称的索引。Because the name and sort key arrays are parallel, the returned index is also the index of the name in the names array.

using System;
using System.Globalization;

public class Example
{
   public static void Main()
   {
      // Define names.
      String[] names= { "Adam", "Ignatius", "Batholomew", "Gregory", 
                        "Clement", "Frances", "Harold", "Dalmatius", 
                        "Edgar", "John", "Benedict", "Paul", "George" }; 
      SortKey[] sortKeys = new SortKey[names.Length];
      CompareInfo ci = CultureInfo.CurrentCulture.CompareInfo;

      for (int ctr = 0; ctr < names.Length; ctr++)
         sortKeys[ctr] = ci.GetSortKey(names[ctr], CompareOptions.IgnoreCase);         
      
      // Sort array based on value of sort keys.
      Array.Sort(names, sortKeys);
      
      Console.WriteLine("Sorted array: ");
      foreach (var name in names)
         Console.WriteLine(name);

      Console.WriteLine();
      
      String[] namesToFind = { "Paul", "PAUL", "Wilberforce" };
      
      Console.WriteLine("Searching an array:");
      foreach (var nameToFind in namesToFind) {
         SortKey searchKey = ci.GetSortKey(nameToFind, CompareOptions.IgnoreCase);
         int index = Array.FindIndex(sortKeys, (x) => x.Equals(searchKey)); 
         if (index >= 0)
            Console.WriteLine("{0} found at index {1}: {2}", nameToFind,
                              index, names[index]);
         else
            Console.WriteLine("{0} not found", nameToFind);
      } 
   }
}
// The example displays the following output:
//       Sorted array:
//       Adam
//       Batholomew
//       Benedict
//       Clement
//       Dalmatius
//       Edgar
//       Frances
//       George
//       Gregory
//       Harold
//       Ignatius
//       John
//       Paul
//       
//       Searching an array:
//       Paul found at index 12: Paul
//       PAUL found at index 12: Paul
//       Wilberforce not found
Imports System.Globalization

Module Example
   Public Sub Main()
      ' Define names.
      Dim names() As String = { "Adam", "Ignatius", "Batholomew", 
                                "Gregory", "Clement", "Frances",  
                                "Harold", "Dalmatius", "Edgar",    
                                "John", "Benedict", "Paul", "George" } 
      Dim sortKeys(names.Length - 1) As SortKey
      Dim ci As CompareInfo = CultureInfo.CurrentCulture.CompareInfo

      For ctr As Integer = 0 To names.Length - 1
         sortKeys(ctr) = ci.GetSortKey(names(ctr), CompareOptions.IgnoreCase)         
      Next   
      
      ' Sort array based on value of sort keys.
      Array.Sort(names, sortKeys)
      
      Console.WriteLine("Sorted array: ")
      For Each name In names
         Console.WriteLine(name)
      Next          
      Console.WriteLine()
      
      Dim namesToFind() As String = { "Paul", "PAUL", "Wilberforce" }
      
      Console.WriteLine("Searching an array:")
      For Each nameToFind In namesToFind
         Dim searchKey As SortKey = ci.GetSortKey(nameToFind, CompareOptions.IgnoreCase)
         Dim index As Integer = Array.FindIndex(sortKeys, 
                                                Function(x) x.Equals(searchKey)) 
         If index >= 0 Then
            Console.WriteLine("{0} found at index {1}: {2}", nameToFind,
                              index, names(index))
         Else
            Console.WriteLine("{0} not found", nameToFind)
         End If                     
      Next                     
   End Sub
End Module
' The example displays the following output:
'       Sorted array:
'       Adam
'       Batholomew
'       Benedict
'       Clement
'       Dalmatius
'       Edgar
'       Frances
'       George
'       Gregory
'       Harold
'       Ignatius
'       John
'       Paul
'       
'       Searching an array:
'       Paul found at index 12: Paul
'       PAUL found at index 12: Paul
'       Wilberforce not found

注解

两个字符串的区分区域性的比较依赖于字符串中具有多个排序权重类别的字符串, 包括脚本、字母、大小写和音调符号权重。A culture-sensitive comparison of two strings depends on each character in the strings having several categories of sort weights, including script, alphabetic, case, and diacritic weights. 排序关键字充当特定字符串的这些权重的存储库。A sort key serves as the repository of these weights for a particular string.

CompareInfo.GetSortKey 方法返回 SortKey 类的实例,它反映指定字符串中字符的区分区域性的映射。The CompareInfo.GetSortKey method returns an instance of the SortKey class that reflects the culture-sensitive mapping of characters in a specified string. SortKey对象的值是它的关键数据, KeyData由属性返回。The value of a SortKey object is its key data, which is returned by the KeyData property. 此密钥数据包含一系列字节, 用于对字符串、特定于区域性的排序规则和用户指定的比较选项进行编码。This key data consists of a series of bytes that encode the string, culture-specific sorting rules, and user-specified comparison options. 使用排序关键字的比较包含每个排序键中相应键数据的按位比较。A comparison using sort keys consists of a bitwise comparison of the corresponding key data in each sort key. 例如,如果您通过调用带 GetSortKey(String, CompareOptions) 的值的 CompareOptions.IgnoreCase 方法来创建一个排序键,则使用该排序键的字符串比较运算不区分大小写。For example, if you create a sort key by calling the GetSortKey(String, CompareOptions) method with a value of CompareOptions.IgnoreCase, a string comparison operation that uses the sort key is case-insensitive.

在创建字符串的排序键之后,可通过调用静态 SortKey.Compare 方法比较排序键。After you create a sort key for a string, you compare sort keys by calling the static SortKey.Compare method. 此方法执行简单的逐字节比较,因此它比 String.CompareCompareInfo.Compare 方法的速度快得多。This method performs a simple byte-by-byte comparison, so it is much faster than the String.Compare or CompareInfo.Compare method.

备注

您可以下载排序权重表、一组文本文件, 其中包含有关在 Windows 操作系统的排序和比较操作中使用的字符权重的信息、默认的Unicode 排序规则元素表、排序适用于 Linux 和 macOS 的权重表。You can download the Sorting Weight Tables, a set of text files that contain information on the character weights used in sorting and comparison operations for Windows operating systems, the Default Unicode Collation Element Table, the sort weight table for Linux and macOS.

性能注意事项Performance considerations

执行字符串比较时,CompareCompareInfo.Compare 方法生成相同的结果,但它们面向不同的方案。When performing a string comparison, the Compare and CompareInfo.Compare methods yield the same results, but they target different scenarios.

在高级别上, 该CompareInfo.Compare方法为每个字符串生成排序键, 执行比较, 然后丢弃排序键并返回比较的结果。At a high level, the CompareInfo.Compare method generates the sort key for each string, performs the comparison, and then discards the sort key and returns the result of the comparison. 但是, 此CompareInfo.Compare方法实际上不会生成整个排序键来执行比较。However, the CompareInfo.Compare method actually doesn't generate an entire sort key to perform the comparison. 相反,此方法将为每个字符串中的每个文本元素(即,基字符、代理项对或组合字符序列)生成关键数据。Instead, the method generates the key data for each text element (that is, base character, surrogate pair, or combining character sequence) in each string. 然后, 方法会比较相应文本元素的键数据。The method then compares the key data for the corresponding text elements. 一旦确定了比较的最终结果, 操作就会终止。The operation terminates as soon as the ultimate result of the comparison is determined. 计算排序键信息, 但不创建SortKey任何对象。Sort key information is computed, but no SortKey object is created. 如果两个字符串比较一次, 则此策略在性能方面是经济实惠的, 但如果将相同的字符串比较过多次, 则此策略会耗费大量时间。This strategy is economical in terms of performance if both strings are compared once, but becomes expensive if the same strings are compared many times.

方法要求在执行比较之前SortKey为每个字符串生成对象。 CompareThe Compare method requires generation of a SortKey object for each string before performing the comparison. 此策略在第一次比较的性能方面开销高昂, 因为需要为生成SortKey对象而投入时间和内存。This strategy is expensive in terms of performance for the first comparison because of the time and memory invested to generate the SortKey objects. 但是, 如果将相同的排序键与多次进行比较, 则会变得很经济。However, it becomes economical if the same sort keys are compared many times.

例如, 假设您编写一个应用程序, 该应用程序在数据库表中搜索与指定的搜索字符串匹配的基于字符串的索引列所在的行。For example, suppose you write an application that searches a database table for the row in which the string-based index column matches a specified search string. 该表包含数以千计的行, 并且将搜索字符串与每行中的索引进行比较需要很长时间。The table contains thousands of rows, and comparing the search string to the index in each row will take a long time. 因此, 当应用程序存储行及其索引列时, 它还会生成并存储列中索引的排序关键字, 以提高搜索性能。Therefore, when the application stores a row and its index column, it also generates and stores the sort key for the index in a column dedicated to improving search performance. 当应用程序搜索目标行时, 它会将搜索字符串的排序关键字与索引字符串的排序键进行比较, 而不是将搜索字符串与索引字符串进行比较。When the application searches for a target row, it compares the sort key for the search string to the sort key for the index string, instead of comparing the search string to the index string.

安全注意事项Security considerations

方法返回一个SortKey对象, 该对象的值基于指定的字符串和CompareOptions值, 以及与基础CompareInfo对象关联的区域性。 CompareInfo.GetSortKey(String, CompareOptions)The CompareInfo.GetSortKey(String, CompareOptions) method returns a SortKey object with the value based on a specified string and CompareOptions value, and the culture associated with the underlying CompareInfo object. 如果安全决策取决于字符串比较或大小写更改,则您应使用固定区域性的 CompareInfo.GetSortKey(String, CompareOptions) 方法来确保操作行为的一致性,无论操作系统的区域性设置如何。If a security decision depends on a string comparison or case change, you should use the CompareInfo.GetSortKey(String, CompareOptions) method of the invariant culture to ensure that the behavior of the operation is consistent, regardless of the culture settings of the operating system.

使用以下步骤获取排序键:Use the following steps to obtain a sort key:

  1. CultureInfo.InvariantCulture 属性中检索固定区域性。Retrieve the invariant culture from the CultureInfo.InvariantCulture property.

  2. CompareInfo 属性中检索固定区域性的 CultureInfo.CompareInfo 对象。Retrieve a CompareInfo object for the invariant culture from the CultureInfo.CompareInfo property.

  3. 调用 CompareInfo.GetSortKey(String, CompareOptions) 方法。Call the CompareInfo.GetSortKey(String, CompareOptions) method.

使用 SortKey 对象的值等效于调用带指定的 LCMAP_SORTKEY 值的 Windows LCMapString 方法。Working with the value of a SortKey object is equivalent to calling the Windows LCMapString method with the LCMAP_SORTKEY value specified. 但是, 对于SortKey对象, 英语字符的排序关键字位于朝鲜语字符的排序关键字之前。However, for the SortKey object, the sort keys for English characters precede the sort keys for Korean characters.

SortKey对象可以进行序列化, 但只能使它们能跨AppDomain对象。SortKey objects can be serialized, but only so that they can cross AppDomain objects. 如果应用程序对 SortKey 对象进行序列化,则此应用程序必须在提供了 .NET Framework 的新版本时重新生成所有排序键。If an application serializes a SortKey object, the application must regenerate all the sort keys when there is a new version of the .NET Framework.

有关排序关键字的详细信息, 请参阅 unicode联合会网站上的 Unicode 技术标准 #10 "Unicode 排序算法"。For more information about sort keys, see Unicode Technical Standard #10, "Unicode Collation Algorithm" on the Unicode Consortium website.

属性

KeyData

获取表示当前 SortKey 对象的字节数组。Gets the byte array representing the current SortKey object.

OriginalString

获取用于创建当前 SortKey 对象的原始字符串。Gets the original string used to create the current SortKey object.

方法

Compare(SortKey, SortKey)

比较两个排序关键字。Compares two sort keys.

Equals(Object)

确定指定的对象是否等于当前 SortKey 对象。Determines whether the specified object is equal to the current SortKey object.

GetHashCode()

用作当前 SortKey 对象的哈希函数,适合用在哈希算法和数据结构(例如哈希表)中。Serves as a hash function for the current SortKey object that is suitable for hashing algorithms and data structures such as a hash table.

GetType()

获取当前实例的 TypeGets the Type of the current instance.

(继承自 Object)
MemberwiseClone()

创建当前 Object 的浅表副本。Creates a shallow copy of the current Object.

(继承自 Object)
ToString()

返回表示当前 SortKey 对象的字符串。Returns a string that represents the current SortKey object.

适用于

另请参阅