English | 简体中文 | 繁體中文 | Русский язык | Français | Español | Português | Deutsch | 日本語 | 한국어 | Italiano | بالعربية

C# SortedList(정렬 목록)

SortedList<TKey, TValue>와 SortedList는 콜렉션 클래스로, 연관된 IComparer 구현에 따라 키에 따라 정렬된 키 값 쌍을 저장할 수 있습니다. 예를 들어, 키가 원시 타입이면 키의 오름차순으로 정렬됩니다.

C#는 generics SortedList < TKey, TValue >와 non-generics SortedList를 모두 지원합니다. 더 빠르고 오류가 적은 generics SortedList < TKey, TValue >를 사용하는 것이 좋습니다.

SortedList 특성

  • SortedList<TKey, TValue>는 키에 따라 정렬된 키 값 쌍 배열입니다

  • 요소가 추가되면 즉시 정렬됩니다. 원시 타입 키는 IComparer<T>에 따라 오름차순으로 정렬되며, 객체 키는 정렬됩니다.

  • System.Collection.Generic 네임스페이스에 속합니다

  • 키는 유일해야 하며 null일 수 없습니다

  • 값은 null이나 중복 될 수 있습니다

  • mySortedList[key] 인덱서에 관련 키를 전달하여 값을 액세스할 수 있습니다

  • KeyValuePair <TKey, TValue>형의 요소를 포함합니다

  • SortedList<TKey, TValue>는 SortedDictionary<TKey, TValue>보다 적은 메모리를 사용합니다.

  • 정렬된 데이터는 검색 속도가 더 빠르며, SortedDictionary<TKey, TValue>는 키 값 쌍 추가와 제거 속도가 더 빠릅니다.

SortedList 생성

다음 예제는 generics SortedList<TKey, TValue>를 생성하고 키 값 쌍을 추가하는 방법을 보여줍니다.

//정수 키 목록, 문자열 값 
SortedList<int, string> numberNames = new SortedList<int, string>();
numberNames.Add(3, "Three");
numberNames.Add(1, "One");
numberNames.Add(2, "Two");
numberNames.Add(4, null);
numberNames.Add(10, "Ten");
numberNames.Add(5, "Five");
//다음은 예외를 일으킬 것입니다
//numberNames.Add("Three", 3); //컴파일 시 오류: 키는 int 타입이어야 합니다
//numberNames.Add(1, "One"); //실행 시 예외: 키 중복
//numberNames.Add(null, "Five");//실행 시 예외: 키는 null이 될 수 없습니다.

위의 예제에서, SortedList<TKey, TValue> 타입의 일반형 SortedList 객체는 저장할 키와 값의 타입을 지정하여 생성됩니다. SortedList<int, string>은 int 타입의 키와 string 타입의 값을 저장합니다.

Add() 메서드는 SortedList에 단일 키 값对人体을 추가합니다. 키는 null이나 중복될 수 없습니다. 존재하면 실행 시 예외가 발생합니다. 값은 중복될 수 있으며, 타입이 null이 될 수 있는 경우 null이 될 수 있습니다.

SortedList 인스턴스를 초기화할 때, COLLECTION 사용-initializer 문법으로 여러 키 값对人体을 초기화합니다. 예를 들어 다음과 같이 합니다.

//문자열 키와 문자열 값을 가진 SortedList 생성 
//COLLECTION 사용-initializer 문법
SortedList<string, string> cities = new SortedList<string, string>()
                                    {
                                        {"London", "UK"},
                                        {"New York", "USA"},
                                        {"Mumbai", "India"},
                                        {"Johannesburg", "South Africa"}
                                    });

SortedList 키 값对人体 추가 후, 키에 따라 키 값对人体을 다시 정렬합니다. 아래 예제는 foreach 루프를 사용하여 모든 키와 값을 표시합니다.

SortedList<int, string> numberNames = new SortedList<int, string>()
                                    {
                                        {3, "Three"},
                                        {5, "Five"},
                                        {1, "One"}
                                    });
Console.WriteLine("---초기 키 값--");
foreach(KeyValuePair<int, string> kvp in numberNames)
    Console.WriteLine("key: {0}, value: {1}1Console.WriteLine("key: {0}, value: {1});
numberNames.Add(6, "Six");
numberNames.Add(2, "Two");
numberNames.Add(4, "Four");
Console.WriteLine("---새로운 키 값对人体 추가 후--");
foreach(var kvp in numberNames)
    Console.WriteLine("key: {0}, value: {1}1Console.WriteLine("key: {0}, value: {1});
출력:
---초기 키 값--
key: 1, value: One
key: 3, value: Three
key: 5, value: Five
---새로운 키 값对人体 추가 후--
key: 1, value: One
key: 2, value: Two
key: 3, value: Three
key: 4, value: Four
key: 5, value: Five
key: 6, value: Six

SortedList 접근

SortedList[key] 인덱서에서 키를 지정하여 SortedList에서 값을 가져오거나 설정합니다.

SortedList<int, string> numberNames = new SortedList<int, string>()
                                    {
                                        {3, "Three"},
                                        {1, "One"},
                                        {2, "Two"
                                    });
Console.WriteLine(numberNames[1]); //출력: One
Console.WriteLine(numberNames[2]); //출력: Two
Console.WriteLine(numberNames[3]); //출력: Three
//Console.WriteLine(numberNames[10]); //실행 시 KeyNotFoundException
numberNames[2] = "TWO"; //값 업데이트
numberNames[4] = "Four"; //키가 존재하지 않으면, 새로운 키 값对人体

위에, numberNames[10]는 지정된 키를 찾을 수 없기 때문에 KeyNotFoundException이 발생합니다}}10sortedlist에서 존재하지 않는 이유. 이 예외를 방지하기 위해 ContainsKey()이나 TryGetValue() 메서드를 사용하십시오. 예를 들어:

SortedList<int, string> numberNames = new SortedList<int, string>()
                                    {
                                        {3, "Three"},
                                        {1, "One"},
                                        {2, "Two"
                                    });
if(numberNames.ContainsKey(4)){
    numberNames[4] = "four";
}
int result;
if(numberNames.TryGetValue(4, out result))
    Console.WriteLine("Key: {0}, Value: {1} 4, result);
출력:
Key:4, Value: Four

for 루프로 SortedList을 반복하려면 Keys와 Values 속성을 사용하십시오.

SortedList<int, string> numberNames = new SortedList<int, string>()
                                    {
                                        {3, "Three"},
                                        {1, "One"},
                                        {2, "Two"
                                    });
for(int i = 0; i < numberNames.Count;++)
{
    Console.WriteLine("key: {0}, value: {1}1}
}
출력:
key: 1, value: One
key: 2, value: Two
key: 3, value: Three

SortedList에서 요소 제거

SortedList에서 키밸류对人体를 Remove(key)과 RemoveAt(index) 메서드로 제거합니다.

SortedList<int, string> numberNames = new SortedList<int, string>()
                                    {
                                        {3, "Three"},
                                        {1, "One"},
                                        {2, "Two"},
                                        {5, "Five"},
                                        {4, "Four"
                                    });
    
numberNames.Remove(1);//키를 제거합니다1네
numberNames.Remove(10);//키를 제거합니다1네, 없으면 오류가 없습니다
numberNames.RemoveAt(0);//INDEX 0에서 키밸류对人体을 제거합니다 
//numberNames.RemoveAt(10);//실행 시 예외: ArgumentOutOfRangeException
foreach(var kvp in numberNames)
	Console.WriteLine("key: {0}, value: {1}1Console.WriteLine("key: {0}, value: {1});
출력:
key: 3, value: Three
key: 4, value: Four
key: 5, value: Five

SortedList 계층 구조

아래 그림은 SortedList 계층 구조를 설명합니다.

SortedList 메서드와 속성에 대한更多信息는 docs.microsoft.com에서 확인할 수 있습니다.