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");
}
}
}
}