C# SortedDictionary.Add() 方法
C# 中的 SortedDictionary.Add() 方法用於向 SortedDictionary<TKey, TValue> 中新增具有指定鍵和值的元素。
語法
語法如下 -
public void Add (TKey key, TValue val);
此處,value key 是要新增的元素的鍵,而 val 是要新增的元素的值。
示例
現在我們來看一個示例 -
using System;
using System.Collections;
using System.Collections.Generic;
public class Demo {
public static void Main(){
SortedDictionary<int, string> sortedDict = new SortedDictionary<int, string>();
sortedDict.Add(100, "Mobile");
sortedDict.Add(200, "Laptop");
sortedDict.Add(300, "Desktop");
sortedDict.Add(400, "Speakers");
sortedDict.Add(500, "Headphone");
sortedDict.Add(600, "Earphone");
Console.WriteLine("SortedDictionary key-value pairs...");
IDictionaryEnumerator demoEnum = sortedDict.GetEnumerator();
while (demoEnum.MoveNext())
Console.WriteLine("Key = " + demoEnum.Key + ", Value = " + demoEnum.Value);
}
}輸出
這將產生以下輸出 -
SortedDictionary key-value pairs... Key = 100, Value = Mobile Key = 200, Value = Laptop Key = 300, Value = Desktop Key = 400, Value = Speakers Key = 500, Value = Headphone Key = 600, Value = Earphone
示例
我們來看另一個示例 -
using System;
using System.Collections;
using System.Collections.Generic;
public class Demo {
public static void Main(){
SortedDictionary<string, string> sortedDict = new SortedDictionary<string, string>();
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("SortedDictionary key-value pairs...");
IDictionaryEnumerator demoEnum = sortedDict.GetEnumerator();
while (demoEnum.MoveNext())
Console.WriteLine("Key = " + demoEnum.Key + ", Value = " + demoEnum.Value);
Console.WriteLine("
The SortedDictionary has the key F? = "+sortedDict.ContainsKey("F"));
}
}輸出
這將產生以下輸出 -
SortedDictionary key-value pairs... Key = A, Value = John Key = B, Value = Andy Key = C, Value = Tim Key = D, Value = Ryan Key = E, Value = Kevin Key = F, Value = Katie Key = G, Value = Brad The SortedDictionary has the key F? = True
廣告
資料結構
網路
RDBMS
作業系統
Java
iOS
HTML
CSS
安卓
Python
C 程式設計
C++
C#
MongoDB
MySQL
Javascript
PHP