SortKey 클래스
정의
중요
일부 정보는 릴리스되기 전에 상당 부분 수정될 수 있는 시험판 제품과 관련이 있습니다. Microsoft는 여기에 제공된 정보에 대해 어떠한 명시적이거나 묵시적인 보증도 하지 않습니다.
문자열을 정렬 키에 매핑한 결과를 나타냅니다.
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" 문화권을 사용하여 문자열 "llama"와 "en-US" 및 "es-ES" 전통 문화권을 비교합니다.
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 훨씬 빠릅니다.
Note
Windows 운영 체제의 정렬 및 비교 작업에 사용되는 문자 가중치에 대한 정보가 포함된 텍스트 파일 집합인 정렬 가중치 테이블, 기본 유니코드 데이터 정렬 요소 테이블, Linux 및 macOS용 정렬 가중치 테이블을 다운로드할 수 있습니다.
성능 고려 사항
문자열 비교를 수행할 때 Compare와 CompareInfo.Compare 메서드는 동일한 결과를 생성하지만, 서로 다른 시나리오에 적합합니다.
상위 수준에서 메서드는 CompareInfo.Compare 각 문자열에 대한 정렬 키를 생성하고 비교를 수행한 다음 정렬 키를 삭제하고 비교 결과를 반환합니다. 그러나 메서드는 CompareInfo.Compare 실제로 비교를 수행하기 위해 전체 정렬 키를 생성하지 않습니다. 대신 메서드는 각 문자열에서 각 텍스트 요소(기본 문자, 서로게이트 쌍 또는 결합 문자 시퀀스)에 대한 키 데이터를 생성합니다. 그런 다음 메서드는 해당 텍스트 요소에 대한 키 데이터를 비교합니다. 비교의 최종 결과가 결정되는 즉시 작업이 종료됩니다. 정렬 키 정보는 계산되지만 개체는 만들어지지 않습니다 SortKey . 이 전략은 두 문자열을 한 번 비교하는 경우 성능 측면에서 경제적이지만 동일한 문자열을 여러 번 비교하면 비용이 많이 듭니다.
이 메서드는 비교를 수행하기 전에 각 문자열에 대해 Compare 개체를 생성해야 합니다. 이 전략은 개체를 생성하는 SortKey 데 투자된 시간과 메모리 때문에 첫 번째 비교의 성능 측면에서 비용이 많이 듭니다. 그러나 동일한 정렬 키를 여러 번 비교하면 경제적이 됩니다.
예를 들어 데이터베이스 테이블에서 문자열 기반 인덱스 열이 지정된 검색 문자열과 일치하는 행을 검색하는 애플리케이션을 작성한다고 가정합니다. 테이블에는 수천 개의 행이 포함되어 있으며 각 행의 인덱스와 검색 문자열을 비교하는 데 시간이 오래 걸릴 수 있습니다. 따라서 애플리케이션이 행과 해당 인덱스 열을 저장하는 경우 검색 성능 향상을 위해 인덱스에 대한 정렬 키도 생성하고 열에 저장합니다. 애플리케이션은 대상 행을 검색할 때 검색 문자열과 인덱스 문자열을 비교하는 대신 검색 문자열의 정렬 키를 인덱스 문자열의 정렬 키와 비교합니다.
보안 고려 사항
이 CompareInfo.GetSortKey(String, CompareOptions) 메서드는 지정된 문자열과 SortKey 값을 바탕으로 한 값을 가지며, 기본 CompareOptions 개체와 연결된 문화권이 있는 CompareInfo 개체를 반환합니다. 보안 결정이 문자열 비교 또는 대/소문자 변경에 따라 달라지는 경우, 운영 체제의 문화권 설정에 관계없이 작업의 동작이 일관되도록 불변 문화권의 CompareInfo.GetSortKey(String, CompareOptions) 메서드를 사용해야 합니다.
정렬 키를 가져오려면 다음 단계를 사용합니다.
CultureInfo.InvariantCulture 속성에서 불변 문화권을 검색합니다.
속성 CompareInfo에서 CultureInfo.CompareInfo 고정 문화권에 대한 개체를 검색합니다.
CompareInfo.GetSortKey(String, CompareOptions) 메서드를 호출합니다.
개체 값 SortKey 으로 작업하는 것은 지정된 LCMAP_SORTKEY 값을 사용하여 Windows LCMapString 메서드를 호출하는 것과 같습니다. 그러나 개체의 SortKey 경우 영어 문자의 정렬 키는 한국어 문자의 정렬 키 앞에 섰습니다.
SortKey 개체는 직렬화할 수 있지만, 이것은 AppDomain 개체를 넘어 전달할 수 있도록 하기 위한 것입니다. 애플리케이션이 개체를 SortKey serialize하는 경우 새 버전의 .NET이 있는 경우 애플리케이션은 모든 정렬 키를 다시 생성해야 합니다.
정렬 키에 대한 자세한 내용은 유니코드 컨소시엄 웹 사이트에서 유니코드 기술 표준 #10, "유니코드 데이터 정렬 알고리즘"을 참조하세요.
속성
| Name | Description |
|---|---|
| KeyData |
현재 SortKey 개체를 나타내는 바이트 배열을 가져옵니다. |
| OriginalString |
현재 SortKey 개체를 만드는 데 사용되는 원래 문자열을 가져옵니다. |
메서드
| Name | Description |
|---|---|
| Compare(SortKey, SortKey) |
두 정렬 키를 비교합니다. |
| Equals(Object) |
지정된 개체가 현재 SortKey 개체와 같은지 여부를 확인합니다. |
| GetHashCode() |
해시 알고리즘 및 해시 테이블과 같은 데이터 구조에 적합한 현재 SortKey 개체에 대한 해시 함수로 사용됩니다. |
| GetType() |
현재 인스턴스의 Type 가져옵니다. (다음에서 상속됨 Object) |
| MemberwiseClone() |
현재 Object단순 복사본을 만듭니다. (다음에서 상속됨 Object) |
| ToString() |
현재 SortKey 개체를 나타내는 문자열을 반환합니다. |