ABOUT ME

-

Today
-
Yesterday
-
Total
-
  • SortedList와 Sorted<TKey, TValue>
    C# 예제 공부일기 2020. 7. 21. 20:48

    Sorted 컬렉션은 키의 오름차순으로 키-값 쌍을 저장한다. 내부적으로 SortedList는 키와 값을 저장하는 두 개의 object[] 배열을 유지한다. 새로운 값이 들어오면 키를 이진탐색하여 적절한 인덱스를 찾고 그 곳에 키 - 값 쌍을 저장한다.

    앞전 예제인 Dictionary를 정렬한 느낌인듯 하다.

     

    C#은 다른 컬렉션과 마찬가지로 제네릭과 제네릭이 아닌 것 두개를 제공한다.

     

    SortedList는 다음과 같이 사용한다. Key는 int , Value는 string이다.

    SortedList<int, string> mySortedList = new SortedList<int, string>();

     

     

    class Program
        {
            static void Main(string[] args)
            {
                SortedList<int, string> s1 = new SortedList<int, string>();
                s1.Add(3, "Three");
                s1.Add(4, "Four");
                s1.Add(1, "One");
                s1.Add(2, "Two"); //s1에 Key인 int값을 기준으로 정렬
    
                for (int i = 0; i < s1.Count; i++)
                {
                    Console.WriteLine("k : {0}, v : {1} /",s1.Keys[i],s1.Values[i]);
                }//인덱스로 접근 가능
                Console.WriteLine();
                Console.WriteLine();
                foreach (var item in s1)
                    Console.Write("{0,-10}", item);
                Console.WriteLine(); //키값인 int형을 기준으로 정렬됨
                Console.WriteLine();
    
                SortedList<string, int> s2 = new SortedList<string, int>();
                s2.Add("One",1);
                s2.Add("Two",2);
                s2.Add("Three", 3);
                s2.Add("Four", 4);
    
                Console.WriteLine("Key가 Two인 Value 값 출력 : {0}", s2["Two"]);
                Console.WriteLine();
                foreach (var item in s2) //키 값인 string 알파벳순으로 정렬
                    Console.Write("{0,-8}", item);
                Console.WriteLine();
                Console.WriteLine();
    
                int val;
                if (s2.TryGetValue("ten", out val)) //ten을 키값으로 가지는 val 출력 하지만 없다.
                    Console.WriteLine("key : ten, value : {0} ", val);
                else 
                    Console.WriteLine(" [ten] : Key is not valid");
                Console.WriteLine();
    
                if (s2.TryGetValue("One", out val)) //one을 키값으로 가지는 val 출력 : 1
                    Console.WriteLine("key : one , value : {0}", val);
    
                Console.WriteLine(s2.ContainsKey("One")); //true
                Console.WriteLine(s2.ContainsKey("ten")); //false
                Console.WriteLine(s2.ContainsValue(2)); //true
                Console.WriteLine(s2.ContainsValue(6)); //false
    
                s2.Remove("One"); //키가 'one' 인 요소 삭제
                s2.RemoveAt(0); //첫번째 요소 삭제
                // 4와 1이 사라짐
                foreach (KeyValuePair<string, int> kvp in s2)
                {
                    Console.Write("{0,-10}", kvp);
                }
                Console.WriteLine();
    
    
    
    
    
            }
    
        }

    요약하자면 SortedList는 키값을 기준으로 자동정렬해주는 Dictionary 같은 느낌이다.

    .Add(Key,Value) 리스트에 요소 추가

    .ContainsKey(Key) 키값이 존재하는지 boolean으로 리턴

    .ContainsValue(Value) 벨류 값이 존재하는지 boolean으로 리턴

    .Remove(Key) 키값 그자체와 그와 쌍으로 존재하는 벨류까지 삭제

    .RemoveAt(index) 인덱스 위치로 삭제

    .TryGetValue(Key, out val) 키에 해당하는 벨류가 있으면 참 없으면 거짓 있다면 val에는 벨류가들어간다.

     

    등등에 대해 공부했다.

Designed by Tistory.