Dictionary 字典类的使用 EnsureCapacity

时间:2021-10-10
本文章向大家介绍Dictionary 字典类的使用 EnsureCapacity,主要包括Dictionary 字典类的使用 EnsureCapacity使用实例、应用技巧、基本知识点总结和需要注意事项,具有一定的参考价值,需要的朋友可以参考一下。

命名空间:System.Collections.Generic 

Dictionary<TKey,TValue>  表示基于键进行组织的键/值对的集合。
List<T>   表示可按索引访问的对象的列表。 提供用于对列表进行搜索、
Queue<T> 表示对象的先进先出 (FIFO) 集合。  
SortedList<TKey,TValue>    表示基于相关的 IComparer<T> 实现按键进行排序的键/ 值对的集合。
Stack<T> 表示对象的后进先出 (LIFO) 集合。

实现键/值对集合

Dictionary<TKey,TValue> 泛型集合可通过每个元素的键访问集合中的元素。 每次对字典的添加都包含一个值和与其关联的键。 通过使用键来检索值十分快捷,因为 Dictionary 类实现为哈希表。以下示例创建 Dictionary 集合并通过使用 foreach 语句循环访问字典。

以下示例使用 ContainsKey 方法和 Dictionary 的 Item[] 属性按键快速查找某个项。 使用 Item 属性可通过 C#

中的 elements[symbol] 来访问 elements 集合中的项。

private static void FindInDictionary(string symbol)
{
Dictionary<string, Element> elements = BuildDictionary();
}
if (elements.ContainsKey(symbol) == false)
{
Console.WriteLine(symbol + " not found");
}
else
{
Element theElement = elements[symbol];
Console.WriteLine("found: " + theElement.Name);
}

内置方法的使用

EnsureCapacity 方法预设一个容量,而无需进一步扩展其后备存储器。 当你知道这个集合最大可能装多少是可以使用该方法。如果集合超过该预设范围 也不会引发异常。

假设需求里一个班最多100个学生,就可以在创建list的时候将容量设置为100。

说白了就是怕内存重新申请和拷贝,List里面存的是引用类型的话,应该影响比较小。不过在确定体量的情况下,先定义容量的话,会比较好。

list 中数组是按照2 4 8 16 这样方式扩容的。扩容后要旧的数组中的内容拷贝到新数组中,当数据大了以后这样就影响性能,然后指针指向新数组,旧数组等待垃圾回收。

  var list = new Dictionary<int,int>();
            list.EnsureCapacity(100);
            for (var i = 0; i < 5; i++)
            {
                list.Add(i,i);
                Console.WriteLine(list[i]);
            }
            list.Add(5,6);
            Console.WriteLine(list[5]);

TryGetValue 方法按键快速查找某个项。

private static void FindInDictionary2(string symbol)
{
Dictionary<string, Element> elements = BuildDictionary();
}
Element theElement = null;
if (elements.TryGetValue(symbol, out theElement) == false)
Console.WriteLine(symbol + " not found");
else
Console.WriteLine("found: " + theElement.Name);

扩展方法

批量添加

List<T> 类有个 AddRange 方法,可以不用 foreach 循环直接向当前集合加入另外一个集合:

List<string> roles = new List<string>();
roles.AddRange(new[] { "role2", "role2" });
roles.AddRange(user.GetRoles());

相当方便,可怜 Dictionary<TKey, TValue> 类没有,幸好有扩展方法:

/// <summary>
/// 向字典中批量添加键值对
/// </summary>
/// <param name="replaceExisted">如果已存在,是否替换</param>
public static Dictionary<TKey, TValue> AddRange<TKey, TValue>(this Dictionary<TKey, TValue> dict, IEnumerable<KeyValuePair<TKey, TValue>> values, bool replaceExisted)
{
    foreach (var item in values)
    {
        if (dict.ContainsKey(item.Key) == false || replaceExisted)
            dict[item.Key] = item.Value;
    }
    return dict;
}

使用示例:

var dict1 = new Dictionary<int, int>()
    .AddOrReplace(2, 2)
    .AddOrReplace(3, 3);
var dict2 = new Dictionary<int, int>()
    .AddOrReplace(1, 1)
    .AddOrReplace(2, 1)
    .AddRange(dict1, false);
编程是个人爱好

原文地址:https://www.cnblogs.com/cdaniu/p/15388974.html