Computer >> Máy Tính >  >> Lập trình >> C#

Phương thức C # SortedDictionary.Add ()


Phương thức SortedDictionary.Add () trong C # được sử dụng để thêm một phần tử có khóa và giá trị đã chỉ định vào SortedDictionary .

Cú pháp

Cú pháp như sau -

 public void Add (TKey key, TValue val); 

Ở trên, khóa giá trị là khóa của phần tử cần thêm, trong khi val là giá trị của phần tử cần thêm.

Ví dụ

Bây giờ chúng ta hãy xem một ví dụ -

 using System; using System.Collections; using System.Collections.Generic; public class Demo {public static void Main () {SortedDictionary  sortedDict =new SortedDictionary  (); sortedDict.Add (100, "Di động"); sortedDict.Add (200, "Máy tính xách tay"); sortedDict.Add (300, "Máy tính để bàn"); sortedDict.Add (400, "Loa"); sortedDict.Add (500, "Tai nghe"); sortedDict.Add (600, "Tai nghe"); Console.WriteLine ("Các cặp khóa-giá trị SortedDictionary ..."); IDictionaryEnumerator demoEnum =sortedDict.GetEnumerator (); while (demoEnum.MoveNext ()) Console.WriteLine ("Key =" + demoEnum.Key + ", Value =" + demoEnum.Value); }} 

Đầu ra

Điều này sẽ tạo ra kết quả sau -

 SortedDictionary key-value ... Key =100, Value =MobileKey =200, Value =LaptopKey =300, Value =DesktopKey =400, Value =SpeakersKey =500, Value =HeadphoneKey =600, Value =Earphone  

Ví dụ

Hãy để chúng tôi xem một ví dụ khác -

 using System; using System.Collections; using System.Collections.Generic; public class Demo {public static void Main () {SortedDictionary  sortedDict =new SortedDictionary  (); sortedDict.Add ("A", "John"); sortedDict.Add ("B", "Andy"); sortedDict.Add ("C", "Tim"); sortedDict.Add ("D", "Ryan"); sortedDict.Add ("E", "Kevin"); sortedDict.Add ("F", "Katie"); sortedDict.Add ("G", "Brad"); Console.WriteLine ("Các cặp khóa-giá trị SortedDictionary ..."); IDictionaryEnumerator demoEnum =sortedDict.GetEnumerator (); while (demoEnum.MoveNext ()) Console.WriteLine ("Key =" + demoEnum.Key + ", Value =" + demoEnum.Value); Console.WriteLine ("\ nSortedDictionary có khóa F? =" + SortedDict.ContainsKey ("F")); }} 

Đầu ra

Điều này sẽ tạo ra kết quả sau -

 SortedDictionary key-value ... Key =A, Value =JohnKey =B, Value =AndyKey =C, Value =TimKey =D, Value =RyanKey =E, Value =KevinKey =F, Value =KatieKey =G , Giá trị =BradThe SortedDictionary có khóa F? =Đúng