C#(99):字典Dictionary<Tkey.TValue>与SortedList

一、概述

表示Key/Value集合,可以添加删除元素,允许按Key来访问元素。是Hashtable的泛型等效类。

它需要一个相等实现来确定键是否相等,可以使用实现了IEqualityComparer<T>的构造函数;如果不指定,默认使用IEqualityComparer<T>.Default。如果Tkey的类型实现了IEuatable<T>,默认相等比较器则会使用该实现。

二、声明及初始化

1、可带初始容量 Dictionary<Tkey,TValue> dic=new Dictionary<Tkey,TValue>([Capacity])

Dictionary<string,string> dic=new Dictionary<string,string>();

2、带泛型接口:Dictionary<Tkey,TValue> dic=new Dictionary<Tkey,TValue>(IEqualityComparer<TKey> comparer)

Dictionary<string, string> dic = new Dictionary<string, string>(StringComparer.CurrentCultureIgnoreCase);

三、常用方法

1、操作元素

添加移除清空键值对:

dic.Add("a", "a1");
dic.Add("b", "b1");
dic.Remove("a");
dic.Clear();

2、判断包含

是否包含指定键指定值:

bool hasKey = dic.ContainsKey("a");
bool hasValue = dic.ContainsValue("a1");

3、赋值或访问

获取指定键的值,如果不存在该键,会产生KeyNotFoundException异常。

string avalue = dic["a"];
string value = "";
if (dic.TryGetValue("a", out value)
{
    Console.Write(value);
}

赋值或添加新元素。

dic["a"] = "a2";

4、遍历

1、遍历整个字典遍历Keys/Values:

foreach (KeyValuePair<string, string> kvp in dic)
{
    Console.Write(kvp.Key);
    Console.Write(kvp.Value);
}
foreach (string key in dic.Keys)
{
    Console.Write(key);
}
foreach (string val in dic.Values)
{
    Console.Write(val);
}

七、KeyValuePair键值对

KeyValuePair是单个的键值对对象。KeyValuePair可用于接收combox选定的值。

KeyValuePair<string, object> par = (KeyValuePair<string, object>)shoplistcomboBox.SelectedItem;

八、SortedList<Tkey,TValue>

可根据Key对集合中的元素进行自动排序。

SortedDictionary<int, string> sDictionary = new SortedDictionary<int, string>();
sDictionary.Add(3, "cc");
sDictionary.Add(4, "dd");
sDictionary.Add(1, "aa");
sDictionary.Add(2, "bb");            // 此处可以发现sDictionary已经自动按key进行了排序

foreach (KeyValuePair<int, string> item in sDictionary)
{
    Console.WriteLine(item.Key + ":" + item.Value);
}

SortedDictionary和SortedList区别:

这两个类的区别在于内存的使用以及插入和移除元素的速度:

  • SortedList 使用的内存比 SortedDictionary 少。
  • SortedDictionary 对执行更快的插入和移除操作.
  • 如果使用排序数据一次性填充列表,则 SortedList 比 SortedDictionary 快。

九、Lookup类

Dictionary<Tkey,TValue>只为每个键支持一个值,新类Lookup<Tkey,TValue>是.NET3.5中新增的,它类似与Dictionary<Tkey,TElement>,但把键映射带一个值集上.这个类在程序及System.Core中实现,用System,Linq命名空间定义。

属性、方法

  • Count:属性Count返回集合中的元素个数
  • Item:使用索引器可以根据键访问特定的元素.因为同一个键可以对应多个值,所以这个属性返回所有值的枚举
  • Contain():方法Contains()根据使用用Key参数传送元素,返回一个布尔值
  • ApplyResultSelector():根据传送给它的转换函数,转换每一项,返回一个集合

Loopup<TKey,TElement>不能像一般的字典那样创建,而必须调用方法ToLookup(),它返回一个Lookup<TKey,TElement>对象。方法ToLookup()是一个扩展方法,可以用于实现了IEnumerable<T>的所有类。

当一个Key要求对应多个value情况ToLookup方法非常有用,ToLookup返回一种特殊的数据结构,类似SQL中的group,可以把集合分组并且可以用索引访问这些元素。

class Package
{
    public string Company;
    public double Weight;
    public long TrackingNumber;
}

void Main()
{
    List<Package> packages = new List<Package> { new Package { Company = "Coho Vineyard", Weight = 25.2, TrackingNumber = 89453312L },
                                                 new Package { Company = "Lucerne Publishing", Weight = 18.7, TrackingNumber = 89112755L },
                                                 new Package { Company = "Wingtip Toys", Weight = 6.0, TrackingNumber = 299456122L },
                                                 new Package { Company = "Contoso Pharmaceuticals", Weight = 9.3, TrackingNumber = 670053128L },
                                                 new Package { Company = "Wide World Importers", Weight = 33.8, TrackingNumber = 4665518773L } };

    //KeySelector,elementSelector
    Lookup<char, string> lookup = (Lookup<char, string>)packages.ToLookup(p => Convert.ToChar(p.Company.Substring(0, 1)), //Key允许有重复值
                                                    p => p.Company + " " + p.TrackingNumber);

    foreach (IGrouping<char, string> packageGroup in lookup)
    {
        Console.WriteLine(packageGroup.Key);
        foreach (string str in packageGroup)
            Console.WriteLine("    {0}", str);
    }
    //KeySelector
    Lookup<char, Package> lookup2 = (Lookup<char, Package>)packages.ToLookup(p => Convert.ToChar(p.Company.Substring(0, 1)));

    foreach (IGrouping<char, Package> packageGroup in lookup2)
    {
        Console.WriteLine(packageGroup.Key);
        foreach (Package p in packageGroup)
            Console.WriteLine("    {0}", p.Company + " " + p.TrackingNumber);
    }

    // 在Lookup根据索引查找元素
    IEnumerable<string> cgroup = lookup['C'];
    foreach (string str in cgroup)
        Console.WriteLine(str);
}

十、线程安全

ConcurrentDictionary

原文地址:https://www.cnblogs.com/springsnow/p/9428525.html