SortedList<TKey, TValue>
運用Add()方法添加鍵與值
如果嘗試訪問的鍵不存在會拋出異常,爲避免可以用ContainsKey()或TryGetValue()
ContainsKey():如果所傳遞的值存在會返回true
TryGetValue():如果指定鍵對應的值不存在,嘗試獲得指定鍵的值
using System;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
namespace 有序列表
{
class Program
{
static void Main(string[] args)
{
var books = new SortedList<string, string>();
books.Add("Key1", "Value1");
books.Add("Key2", "Value2");
books["Key3"] = "Value3";
books["Key4"] = "Value4";
foreach (KeyValuePair<string,string> book in books)
{
Console.WriteLine($"{book.Key} {book.Value}");
}
//foreach (string isbn in books.Values)
//{
// Console.WriteLine(isbn);
//}
//foreach (string title in books.Keys)
//{
// Console.WriteLine(title);
//}
string title = "Key5";
if(!books.TryGetValue(title,out string isbn))
{
Console.WriteLine($"{title} not found");
}
if (!books.ContainsKey(title))
{
Console.WriteLine($"{title} not found");
}
}
}
}