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
屬性

範例

下列範例會比較字串 "llama" 使用 "en-us" 和 "es" 文化特性,以及 "en-us" 和 "es" 傳統文化特性。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. 例如,如果您藉由呼叫 CompareOptions.IgnoreCase值的 GetSortKey(String, CompareOptions) 方法來建立排序索引鍵,則使用排序關鍵字的字串比較作業不會區分大小寫。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.

Compare 方法必須先為每個字串產生 SortKey 物件,然後再執行比較。The 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

CompareInfo.GetSortKey(String, CompareOptions) 方法會根據指定的字串和 CompareOptions 值,以及與基礎 CompareInfo 物件相關聯的文化特性,傳回具有值的 SortKey 物件。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. CultureInfo.CompareInfo 屬性取得不因文化特性而異的 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 物件的值相當於呼叫 Windows LCMapString 方法並指定 LCMAP_SORTKEY 值。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.

適用於

另請參閱