1. 程式人生 > 其它 >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);
程式設計是個人愛好