SortKey 类

定义

表示将字符串映射到其排序键的结果。

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

示例

以下示例使用“en-US”和“es-ES”区域性以及“en-US”和“es-ES”传统文化比较字符串“llama”。

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 类来提高应用程序的性能,这些应用程序依赖于对大型数组进行排序和搜索。 此示例创建名称的无序数组,在本例中,该数组包含 13 个元素。 然后,它将每个名称的排序键存储在并行数组中,该数组将 Sort(Array, Array) 传递给该方法。 结果是已排序的数组。 然后,该示例在数组中搜索三个字符串。 对于每个搜索字符串,它调用 GetSortKey(String, CompareOptions) 该方法来检索字符串的排序键,然后调用 Array.FindIndex 该方法以检索排序键数组中该排序键的索引。 由于名称和排序键数组是并行的,因此返回的索引也是数组中 names 名称的索引。

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

注解

区分区域性的两个字符串比较取决于字符串中的每个字符,这些字符具有多个类别的排序权重,包括脚本、字母、大小写和变音符号权重。 排序键用作特定字符串的这些权重的存储库。

CompareInfo.GetSortKey 方法返回 SortKey 类的一个实例,该实例反映指定字符串中字符的文化敏感映射。 SortKey 对象的值是其键数据,这是由 KeyData 属性返回的。 此键数据由一系列字节组成,这些字节对字符串、区域性特定的排序规则和用户指定的比较选项进行编码。 使用排序键的比较包括每个排序键中相应键数据的按位比较。 例如,如果通过调用GetSortKey(String, CompareOptions)方法并传入CompareOptions.IgnoreCase值来创建排序键,则使用该排序键的字符串比较将不区分大小写。

为字符串创建排序键后,可以通过调用静态 SortKey.Compare 方法比较排序键。 此方法执行逐字节比较,因此比 String.CompareCompareInfo.Compare 方法快得多。

注释

可以下载 排序权重表,它是一组文本文件,其中包含 Windows 操作系统的排序和比较操作中使用的字符权重信息、默认 Unicode 排序规则元素表 和 Linux 与 macOS 的排序权重表。

性能注意事项

执行字符串比较时, CompareCompareInfo.Compare 方法产生相同的结果,但它们面向不同的方案。

在高级别上,该方法 CompareInfo.Compare 为每个字符串生成排序键,执行比较,然后放弃排序键并返回比较结果。 但是,该方法 CompareInfo.Compare 实际上不会生成执行比较的整个排序键。 相反,该方法为每个文本元素(即基字符、代理项对或组合字符序列)在每个字符串中生成键数据。 然后,该方法比较相应文本元素的键数据。 确定比较的最终结果后,该操作将立即终止。 将计算排序关键字信息,但不会创建 SortKey 对象。 如果两个字符串都比较一次,则此策略在性能方面是经济的,但如果多次比较相同的字符串,则成本会变得昂贵。

在执行比较之前,该方法 Compare 需要为每个字符串生成一个 SortKey 对象。 由于需要花费时间和内存来生成 SortKey 对象,因此第一次比较时,此策略的性能非常昂贵。 但是,如果多次比较相同的排序键,它将变得更加划算。

例如,假设你编写一个应用程序,该应用程序在数据库表中搜索基于字符串的索引列与指定的搜索字符串匹配的行。 该表包含数千行,并将搜索字符串与每行中的索引进行比较需要很长时间。 因此,当应用程序存储行及其索引列时,它还会在专用于提高搜索性能的列中生成和存储索引的排序键。 当应用程序搜索目标行时,它将搜索字符串的排序键与索引字符串的排序键进行比较,而不是将搜索字符串与索引字符串进行比较。

安全注意事项

CompareInfo.GetSortKey(String, CompareOptions) 方法会返回一个 SortKey 对象,该对象基于指定的字符串和 CompareOptions 值以及与基础 CompareInfo 对象关联的区域性生成。 如果安全决策取决于字符串比较或大小写更改,则您应使用固定区域性的 CompareInfo.GetSortKey(String, CompareOptions) 方法来确保操作行为的一致性,无论操作系统的区域性设置如何。

使用以下步骤获取排序键:

  1. CultureInfo.InvariantCulture 属性中检索不变的文化信息。

  2. CompareInfo 属性中检索固定区域性的 CultureInfo.CompareInfo 对象。

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

使用 SortKey 对象的值等效于调用带指定的 LCMAP_SORTKEY 值的 Windows LCMapString 方法。 但是,对于 SortKey 对象,英语字符的排序键位于朝鲜字符的排序键前面。

SortKey 对象可以序列化,但这是为了能够跨越 AppDomain 对象。 如果应用程序序列化对象 SortKey ,则当有新版本的 .NET 时,应用程序必须重新生成所有排序键。

有关排序键的详细信息,请参阅 Unicode 联盟网站上的 Unicode 技术标准 #10、“Unicode 排序规则算法”。

属性

名称 说明
KeyData

获取表示当前 SortKey 对象的字节数组。

OriginalString

获取用于创建当前 SortKey 对象的原始字符串。

方法

名称 说明
Compare(SortKey, SortKey)

比较两个排序键。

Equals(Object)

确定指定的对象是否等于当前 SortKey 对象。

GetHashCode()

用作适用于哈希算法和数据结构(如哈希表)的当前 SortKey 对象的哈希函数。

GetType()

获取当前实例的 Type

(继承自 Object)
MemberwiseClone()

创建当前 Object的浅表副本。

(继承自 Object)
ToString()

返回一个表示当前 SortKey 对象的字符串。

适用于

另请参阅