您的位置:首页 > 其它

你能熟练使用Dictionary字典和List列表吗?

2012-03-03 23:42 323 查看
命名空间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();
}
}
}

复制代码

  程序输出结果:

内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: