วันพฤหัสบดีที่ 20 ตุลาคม พ.ศ. 2565

การใช้ SortedDictionary

 //Microsoft (R) Visual C# Compiler version 3.4.0-beta4-19562-05 (ff930dec)

//Copyright (C) Microsoft Corporation. All rights reserved.



using System;

using System.Collections.Generic;

using System.Linq;

using System.Text.RegularExpressions;


namespace Rextester

{

    

     

    public class Program

    {

        

       public class scompare :IComparer <string>{

         public  int Compare(string x, string y)

        {

            if (x.Length > y.Length)

            {

                return -1;

            }

            else

            {

                return 1;

            }

        }

        }

        public static void Main(string[] args)

        {

         // a new sorted dictionary is created with key type string and value type string

SortedDictionary<string, string> tam = new SortedDictionary<string, string>(new scompare());

// using add method in dictionary to add the objects to the dictionary

tam.Add("R12", "Red");

    tam.Add("kk2s2","kk");       

tam.Add("G345", "Green1111");

tam.Add("Y1", "Yellow");

// a foreach loop is used to loop around every key in the dictionary and to obtain each key value

foreach(KeyValuePair<string,string>ra in tam)

{

Console.WriteLine("The key and value pairs is SortedDictionary are = {0} and {1}", ra.Key, ra.Value);

}

//using clear method to remove all the objects from sorted dictionary

tam.Clear();

foreach(KeyValuePair<string,string>tr in tam)

{

Console.WriteLine("The key and value pairs is SortedDictionary are = {0} and {1}", tr.Key, tr.Value);

}

}

        }     

    }