c# 遍歷 Dictionary的四種方式
一:背景
1. 講故事
昨天在 StackOverflow 上看到一個很有趣的問題,說: 你會幾種遍歷字典的方式,然后跟帖就是各種奇葩的回答,挺有意思,馬上就要國慶了,娛樂娛樂吧,說說這種挺無聊的問題😄😄😄。
二: 使用 foreach 遍歷
為了方便演示,先上一段測試代碼:
var dict = new Dictionary<int, string>() { [10] = "A10", [20] = "A20", [30] = "A30", [40] = "A40", [50] = "A50" };
1. 直接 foreach dict
如果要拿百分比說話,估計有 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; } } }
2. foreach 中 使用 KeyPairValue 解構(gòu)
剛才你也看到了 item 是 KeyValuePair 類型,不過🐂👃的是 netcore 對 KeyValuePair 進行了增強,增加了 Deconstruct 函數(shù)用來解構(gòu) 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; } }
有了這個解構(gòu)函數(shù),你就可以在遍歷的過程中直接拿到 key,value,而不是包裝的 KeyValuePair,這在 netframework 中可是不行的哈,實現(xiàn)代碼如下:
foreach ((int key, string value) in dict) { Console.WriteLine($"key={key},value={value}"); }
3. foreach keys
前面的例子都是直接對 dict 進行 foreach,其實你還可以對 dict.keys 進行 foreach 遍歷,然后通過遍歷出的 key 對 dict 進行類索引器讀取,代碼如下:
foreach (var key in dict.Keys) { Console.WriteLine($"key={key},value={dict[key]}"); }
仔細(xì)看這個 while 循環(huán),你就應(yīng)該明白,本質(zhì)上它也是對 entries 數(shù)組進行遍歷,那底層都用了 while,我是不是可以用 for 來替換然后循環(huán) dict 呢?哈哈,反正就是模仿唄。
三:使用 for 遍歷
為了把 MoveNext 中的代碼模擬出來,重點在于這條語句: ref Entry reference = ref _dictionary._entries[_index++];, 其實很簡單,_entries 數(shù)組內(nèi)容的提取可以用 Linq 的 ElementAt 方法,是不是~~~ ,改造后的代碼如下:
for (int i = 0; i < dict.Count; i++) { (int key, string value) = dict.ElementAt(i); Console.WriteLine($"key={key},value={dict[key]}"); }
接下來是不是很好奇這個 ElementAt 擴展方法是如何實現(xiàn)的,一起看看源碼吧。
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--; } } } }
從上面代碼可以看到,如果當(dāng)前的 source 沒有實現(xiàn) IList 接口的話,那就是一個巨大的坑,每一次執(zhí)行 ElementAt 方法,最壞時間復(fù)雜度都是 O(N),就拿剛才的 for循環(huán)來說,它的最壞時間復(fù)雜度就是 O(n!) ,是不是比你想象的要恐怖的多,教訓(xùn)就是多實踐,多看看源碼~
四:總結(jié)
這篇列舉了 4 種遍歷 dict 的方式,不知你會用到哪幾種? 要注意的是最后 ElementAt 對 Source 判別上的大坑一定要明白,不要想當(dāng)然的以為就是 O(N) ,好了,更多的 遍歷方式 歡迎補充!
以上就是c# 遍歷 Dictionary的四種方式的詳細(xì)內(nèi)容,更多關(guān)于c# 遍歷 Dictionary的資料請關(guān)注腳本之家其它相關(guān)文章!
相關(guān)文章
c# 免費組件html轉(zhuǎn)pdf的實現(xiàn)過程
這篇文章主要介紹了c# 免費組件html轉(zhuǎn)pdf的實現(xiàn)過程,具有很好的參考價值,希望對大家有所幫助。如有錯誤或未考慮完全的地方,望不吝賜教2022-06-06C#實現(xiàn)ArrayList動態(tài)數(shù)組的示例
ArrayList是一個動態(tài)數(shù)組,可以用來存儲任意類型的元素,本文就來介紹一下C#實現(xiàn)ArrayList動態(tài)數(shù)組的示例,具有一定的參考價值,感興趣的可以了解一下2023-12-12C#實現(xiàn)Array,List,Dictionary相互轉(zhuǎn)換
這篇文章介紹了C#實現(xiàn)Array,List,Dictionary互相轉(zhuǎn)換的方法,文中通過示例代碼介紹的非常詳細(xì)。對大家的學(xué)習(xí)或工作具有一定的參考借鑒價值,需要的朋友可以參考下2022-04-04C#結(jié)合JavaScript實現(xiàn)多文件上傳功能
在許多應(yīng)用場景里,多文件上傳是一項比較實用的功能,本文主要為大家詳細(xì)介紹了C#如何結(jié)合JavaScript實現(xiàn)多文件上傳功能,感興趣的小伙伴可以了解下2023-12-12