昨天在 StackOverflow 上看到一個頗有趣的問題,說: 你會幾種遍歷字典的方式,而後跟帖就是各類奇葩的回答,挺有意思,立刻就要國慶了,娛樂娛樂吧,說說這種挺無聊的問題😄😄😄。git
爲了方便演示,先上一段測試代碼:github
var dict = new Dictionary<int, string>() { [10] = "A10", [20] = "A20", [30] = "A30", [40] = "A40", [50] = "A50" };
若是要拿百分比說話,估計有 50%+ 的小夥伴用這種方式,爲啥,簡單粗暴唄,其餘沒什麼好說的,直接上代碼:數組
foreach (var item in dict) { Console.WriteLine($"key={item.Key},value={item.Value}"); }
這裏的 item 是底層在 MoveNext 的過程當中用 KeyValuePair 包裝出來的,若是你不信的話,看下源碼唄:函數
public bool MoveNext() { while ((uint)_index < (uint)_dictionary._count) { ref Entry reference = ref _dictionary._entries[_index++]; if (reference.next >= -1) { _current = new KeyValuePair<TKey, TValue>(reference.key, reference.value); return true; } } }
剛纔你也看到了 item 是 KeyValuePair 類型,不過🐂👃的是 netcore 對 KeyValuePair 進行了加強,增長了 Deconstruct 函數用來解構 KeyValuePair,代碼以下:測試
public readonly struct KeyValuePair<TKey, TValue> { private readonly TKey key; private readonly TValue value; public TKey Key => key; public TValue Value => value; public KeyValuePair(TKey key, TValue value) { this.key = key; this.value = value; } public void Deconstruct(out TKey key, out TValue value) { key = Key; value = Value; } }
有了這個解構函數,你就能夠在遍歷的過程當中直接拿到 key,value,而不是包裝的 KeyValuePair,這在 netframework 中但是不行的哈,實現代碼以下:ui
foreach ((int key, string value) in dict) { Console.WriteLine($"key={key},value={value}"); }
前面的例子都是直接對 dict 進行 foreach,其實你還能夠對 dict.keys 進行 foreach 遍歷,而後經過遍歷出的 key 對 dict 進行類索引器讀取,代碼以下:this
foreach (var key in dict.Keys) { Console.WriteLine($"key={key},value={dict[key]}"); }
說到這裏,不知道你是否有一個潛意識,那就是 dict 只能經過 foreach 進行遍歷,真相是否是這樣的呢? 要尋找答案,仍是回頭看一下 foreach 是如何進行遍歷的。spa
public struct Enumerator : IEnumerator<KeyValuePair<TKey, TValue>>, IDisposable, IEnumerator, IDictionaryEnumerator { public bool MoveNext() { while ((uint)_index < (uint)_dictionary._count) { ref Entry reference = ref _dictionary._entries[_index++]; if (reference.next >= -1) { _current = new KeyValuePair<TKey, TValue>(reference.key, reference.value); return true; } } _index = _dictionary._count + 1; _current = default(KeyValuePair<TKey, TValue>); return false; } }
仔細看這個 while 循環,你就應該明白,本質上它也是對 entries 數組進行遍歷,那底層都用了 while,我是否是能夠用 for 來替換而後循環 dict 呢?哈哈,反正就是模仿唄。code
爲了把 MoveNext 中的代碼模擬出來,重點在於這條語句: ref Entry reference = ref _dictionary._entries[_index++];
, 其實很簡單,_entries 數組內容的提取能夠用 Linq 的 ElementAt 方法,是否是~~~ ,改造後的代碼以下:blog
for (int i = 0; i < dict.Count; i++) { (int key, string value) = dict.ElementAt(i); Console.WriteLine($"key={key},value={dict[key]}"); }
接下來是否是很好奇這個 ElementAt 擴展方法是如何實現的,一塊兒看看源碼吧。
public static TSource ElementAt<TSource>(this IEnumerable<TSource> source, int index) { IList<TSource> list = source as IList<TSource>; if (list != null) { return list[index]; } if (index >= 0) { using (IEnumerator<TSource> enumerator = source.GetEnumerator()) { while (enumerator.MoveNext()) { if (index == 0) { return enumerator.Current; } index--; } } } }
從上面代碼能夠看到,若是當前的 source 沒有實現 IList 接口的話,那就是一個巨大的坑,每一次執行 ElementAt 方法,最壞時間複雜度都是 O(N),就拿剛纔的 for循環來講,它的最壞時間複雜度就是 O(n!) ,是否是比你想象的要恐怖的多,教訓就是多實踐,多看看源碼~
這篇列舉了 4 種遍歷 dict 的方式,不知你會用到哪幾種? 要注意的是最後 ElementAt 對 Source 判別上的大坑必定要明白,不要想固然的覺得就是 O(N) ,好了,更多的 遍歷方式 歡迎補充!
更多高質量乾貨:參見個人 GitHub: dotnetfly