Dictionary泛型集合,从字面上看,即字典序集合。它提供了一组关键字到一组值的映射。下面是它的一些用法和属性。
方法和属性 | 说明 |
Add(Key, Value) | 添加 |
TryGetValue(Key, out value) | 取值:若有,返回true,value存放结果;否则返回false。 |
ContainsKey(Key) | 判断是否包含该关键字:是,返回true;否则,false |
Remove(Key) | 移除某个元素 |
Clear() | 清除该集合所有元素 |
DictionaryValueName[Key] | 通过关键字访问 |
DictionaryValueName.Keys | 取关键字Key集合 |
DictionaryValueName.Values | 取Value集合 |
DictionaryValueName.Count | 集合元素个数 |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace DictionaryTest
{
class Program
{
static void Main(string[] args)
{
Dictionary<string, string> dictionary = new Dictionary<string, string>();
//添加
dictionary.Add("01", "int");
dictionary.Add("02", "double");
dictionary.Add("03", "string");
dictionary.Add("04", "long");
//遍历
foreach (KeyValuePair<string, string> kv in dictionary)
{
Console.WriteLine(string.Format("Key:{0}, Value:{1}", kv.Key, kv.Value));
}
Console.WriteLine();
//判断是否包含关键字“05”,不包含则先添加
if (!dictionary.ContainsKey("05"))
{
dictionary.Add("05", "DataSet");
}
//用关键字做下标访问集合元素
Console.WriteLine(string.Format("New Element: Key:{0}, Value:{1}", "05", dictionary["05"]));
//修改指定元素
dictionary["05"] = "bool";
Console.WriteLine(string.Format("After Alter: Key:{0}, Value:{1}", "05", dictionary["05"]));
Console.WriteLine();
//获取value值
string value = "";
if (dictionary.TryGetValue("03", out value))
{
Console.WriteLine(string.Format("Get Element: Key:{0}, Value:{1}", "03", value));
}
else
{
Console.WriteLine("不存在该关键字。");
}
Console.WriteLine();
//获取关键字key集合
Dictionary<string, string>.KeyCollection keys = dictionary.Keys;
//获取值value集合
Dictionary<string, string>.ValueCollection values = dictionary.Values;
string strShow = "关键字集合:";
foreach (string k in keys)
{
strShow += k + ", ";
}
Console.WriteLine(strShow.TrimEnd(',', ' '));
strShow = "值集合:";
foreach (string v in values)
{
strShow += v + ", ";
}
Console.WriteLine(strShow.TrimEnd(',', ' '));
Console.WriteLine();
//删除某个关键字
dictionary.Remove("05");
if (!dictionary.ContainsKey("05"))
{
Console.WriteLine("关键字“05”已删除。");
}
//删除整个集合
dictionary.Clear();
if (dictionary.Count == 0)
{
Console.WriteLine("该集合元素已清空。");
}
}
}
}