你能熟練使用Dictionary字典和List列表嗎?


  命名空間System.Collections.Generic中有兩個非常重要,而且常用的泛型集合類,它們分別是Dictionary<TKey,TValue>字典和List<T>列表。Dictionary字典通常用於保存鍵/值對的數據,而List列表通中用於保存可通過索引訪問的對象的強類型列表。下面來總結一下,用代碼來演示怎么初始化,增加,修改,刪除和遍歷元素。

Dictionary<TKey,TValue>字典

  代碼如下:

namespace DictionaryDemo1
{
class Program
{
static void Main(string[] args)
{
//創建Dictionary<TKey,TValue>對象
Dictionary<string, string> openWith = new Dictionary<string, string>();

//添加元素到對象中,共有兩種方法。注意,字典中的鍵不可以重復,但值可以重復。
//方法一:使用對象的Add()方法
openWith.Add("txt", "notepad.exe");
openWith.Add("bmp", "paint.exe");
openWith.Add("dib", "paint.exe");
openWith.Add("rtf", "wordpad.exe");

//方法二:使用索引器Indexer
//openWith["txt"] = "notepad.exe";
//openWith["bmp"] = "paint.exe";
//openWith["dib"] = "paint.exe";
//openWith["rtf"] = "wordpad.exe";

//增加元素,注意增加前必須檢查要增加的鍵是否存在使用ContainsKey()方法
if (!openWith.ContainsKey("ht"))
{
openWith.Add("ht", "hypertrm.exe");//或openWith["ht"] = "hypertrm.exe";
Console.WriteLine("增加元素成功!Key={0},Value={1}","ht",openWith["ht"]);
}

//刪除元素,使用Remove()方法
if (openWith.ContainsKey("rtf"))
{
openWith.Remove("rtf");
Console.WriteLine("刪除元素成功!鍵為rtf");
}

if (!openWith.ContainsKey("rtf"))
{
Console.WriteLine("Key=\"rtf\"的元素找不到!");
}

//修改元素,使用索引器
if (openWith.ContainsKey("txt"))
{
openWith["txt"] = "notepadUpdate.exe";
Console.WriteLine("修改元素成功!Key={0},Value={1}", "txt", openWith["txt"]);
}

//遍歷元素,因為該類實現了IEnumerable接口,所以可以使用foreach語句,注意元素類型是 KeyValuePair(Of TKey, TValue)
foreach (KeyValuePair<string, string> kvp in openWith)
{
Console.WriteLine("Key={0},Value={1}",kvp.Key,kvp.Value);
}

Console.WriteLine("遍歷元素完成!");
Console.ReadKey();
}
}
}

  程序輸出結果:

List<T>列表

  代碼如下:

namespace ListDemo1
{
class Program
{
static void Main(string[] args)
{
//創建List<T>列表對象
List<string> dinosaurs = new List<string>();

//增加元素到列表(或稱為初始化),注意初始化時不能使用索引器,因為沒有增加元素之前list列表是空的
dinosaurs.Add("Tyrannosaurus");
dinosaurs.Add("Amargasaurus");
dinosaurs.Add("Mamenchisaurus");
dinosaurs.Add("Deinonychus");
dinosaurs.Add("Compsognathus");

//一個重要屬性
Console.WriteLine("列表中的元素數為: {0}", dinosaurs.Count);//獲取 List 中實際包含的元素數


//插入元素,使用Insert()方法
dinosaurs.Insert(2, "Compsognathus");//將元素插入到指定索引處,原來此位置的元素后移
Console.WriteLine("在索引為2的位置插入了元素{0}",dinosaurs[2]);

//刪除元素,使用Remove()方法
dinosaurs.Remove("Compsognathus");//從 List 中移除特定對象的第一個匹配項
Console.WriteLine("刪除第一個名為Compsognathus的元素!");

//修改元素,使用索引器
dinosaurs[0] = "TyrannosaurusUpdate";
Console.WriteLine("修改索引為0的元素成功!");

//遍歷元素,使用foreach語句,元素類型為string
foreach (string dinosaur in dinosaurs)
{
Console.WriteLine(dinosaur);
}

Console.WriteLine("遍歷元素完成!");
Console.ReadKey();
}
}
}

  程序輸出結果:


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM