成人免费xxxxx在线视频软件_久久精品久久久_亚洲国产精品久久久_天天色天天色_亚洲人成一区_欧美一级欧美三级在线观看

遍歷 Dictionary,你會幾種方式?

開發(fā) 前端
昨天在 StackOverflow 上看到一個很有趣的問題,說: 你會幾種遍歷字典的方式,然后跟帖就是各種奇葩的回答,挺有意思,馬上就要國慶了,娛樂娛樂吧,說說這種挺無聊的問題。

一:背景

1. 講故事

[[344323]]

昨天在 StackOverflow 上看到一個很有趣的問題,說: 你會幾種遍歷字典的方式,然后跟帖就是各種奇葩的回答,挺有意思,馬上就要國慶了,娛樂娛樂吧,說說這種挺無聊的問題。

二: 使用 foreach 遍歷

為了方便演示,先上一段測試代碼:

  1. var dict = new Dictionary<int, string>() 
  2.             {                [10] = "A10"
  3.                 [20] = "A20"
  4.                 [30] = "A30"
  5.                 [40] = "A40"
  6.                 [50] = "A50" 
  7.             }; 

1. 直接 foreach dict

如果要拿百分比說話,估計有 50%+ 的小伙伴用這種方式,為啥,簡單粗暴唄,其他沒什么好說的,直接上代碼:

  1. foreach (var item in dict) 
  2.            {                Console.WriteLine($"key={item.Key},value={item.Value}"); 
  3.            } 

 

遍歷 Dictionary,你會幾種方式?

這里的 item 是底層在 MoveNext 的過程中用 KeyValuePair 包裝出來的,如果你不信的話,看下源碼唄:

  1. public bool MoveNext() 
  2.    {        while ((uint)_index < (uint)_dictionary._count) 
  3.        {            ref Entry reference = ref _dictionary._entries[_index++]; 
  4.            if (reference.next >= -1) 
  5.            {                _current = new KeyValuePair<TKey, TValue>(reference.key, reference.value); 
  6.                return true
  7.            }        }    } 

2. foreach 中 使用 KeyPairValue 解構(gòu)

剛才你也看到了 item 是 KeyValuePair 類型,不過的是 netcore 對 KeyValuePair 進行了增強,增加了 Deconstruct 函數(shù)用來解構(gòu) KeyValuePair,代碼如下:

  1. public readonly struct KeyValuePair<TKey, TValue> 
  2.     {        private readonly TKey key
  3.         private readonly TValue value; 
  4.         public TKey Key => key
  5.         public TValue Value => value; 
  6.         public KeyValuePair(TKey key, TValue value) 
  7.         {            this.key = key
  8.             this.value = value; 
  9.         }        public void Deconstruct(out TKey keyout TValue value) 
  10.         {            key = Key;            value = Value; 
  11.         }    } 

有了這個解構(gòu)函數(shù),你就可以在遍歷的過程中直接拿到 key,value,而不是包裝的 KeyValuePair,這在 netframework 中可是不行的哈,實現(xiàn)代碼如下:

  1. foreach ((int key, string value) in dict) 
  2.             {                Console.WriteLine($"key={key},value={value}"); 
  3.             } 

 

遍歷 Dictionary,你會幾種方式?

3. foreach keys

前面的例子都是直接對 dict 進行 foreach,其實你還可以對 dict.keys 進行 foreach 遍歷,然后通過遍歷出的 key 對 dict 進行類索引器讀取,代碼如下:

  1. foreach (var key in dict.Keys) 
  2.           {                Console.WriteLine($"key={key},value={dict[key]}"); 
  3.           } 

 

遍歷 Dictionary,你會幾種方式?

說到這里,不知道你是否有一個潛意識,那就是 dict 只能通過 foreach 進行遍歷,真相是不是這樣的呢? 要尋找答案,還是回頭看一下 foreach 是如何進行遍歷的。

  1. public struct Enumerator : IEnumerator<KeyValuePair<TKey, TValue>>, IDisposable, IEnumerator, IDictionaryEnumerator 
  2. {    public bool MoveNext() 
  3.     {        while ((uint)_index < (uint)_dictionary._count) 
  4.         {            ref Entry reference = ref _dictionary._entries[_index++]; 
  5.             if (reference.next >= -1) 
  6.             {                _current = new KeyValuePair<TKey, TValue>(reference.key, reference.value); 
  7.                 return true
  8.             }        }        _index = _dictionary._count + 1; 
  9.         _current = default(KeyValuePair<TKey, TValue>); 
  10.         return false
  11.     }} 

仔細看這個 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 方法,是不是~ ,改造后的代碼如下:

  1. for (int i = 0; i < dict.Count; i++) 
  2. {                (int key, string value) = dict.ElementAt(i); 
  3.     Console.WriteLine($"key={key},value={dict[key]}"); 

 

遍歷 Dictionary,你會幾種方式?

接下來是不是很好奇這個 ElementAt 擴展方法是如何實現(xiàn)的,一起看看源碼吧。

  1. public static TSource ElementAt<TSource>(this IEnumerable<TSource> source, int index
  2. {        IList<TSource> list = source as IList<TSource>; 
  3.     if (list != null
  4.     {            return list[index]; 
  5.     }        if (index >= 0) 
  6.     {            using (IEnumerator<TSource> enumerator = source.GetEnumerator()) 
  7.         {                while (enumerator.MoveNext()) 
  8.             {                    if (index == 0) 
  9.                 {                        return enumerator.Current
  10.                 }                    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) ,好了,更多的 遍歷方式 歡迎補充!

責(zé)任編輯:未麗燕 來源: 今日頭條
相關(guān)推薦

2021-05-07 16:19:36

異步編程Java線程

2023-05-08 15:57:16

二叉樹數(shù)據(jù)結(jié)構(gòu)

2024-05-10 07:44:23

C#進程程序

2022-05-27 06:57:50

Python循環(huán)方式生成器

2024-02-05 12:08:07

線程方式管理

2022-05-18 10:38:51

Redis分布式鎖數(shù)據(jù)

2023-09-29 11:29:12

Spring異常處理類

2018-11-08 09:09:37

Linux系統(tǒng)恢復(fù)

2019-07-23 17:52:59

Spring BootJava開發(fā)

2025-01-21 10:04:40

Java并發(fā)阻塞隊列

2022-03-28 20:57:31

私有屬性class屬性和方法

2019-07-23 15:56:56

Spring Boot部署servlet

2023-10-30 11:53:37

繼承JS父類

2020-09-07 08:00:48

2014-02-18 10:59:52

nftablesLinux 3.13

2024-11-04 09:39:08

Java?接口Thread?類

2019-12-17 08:45:30

ifelseJava

2024-04-24 11:24:43

C#數(shù)據(jù)去重

2021-12-15 23:10:34

JS Debugger 前端開發(fā)

2024-06-12 08:05:06

點贊
收藏

51CTO技術(shù)棧公眾號

主站蜘蛛池模板: 亚洲第一中文字幕 | 国产成人a亚洲精品 | 日韩视频在线一区 | 国产乱码精品一品二品 | 欧美一区精品 | 九九综合 | 精品久久一区二区 | 不用播放器看的av | 成人久久一区 | 成人二区三区 | 91亚洲精品久久久电影 | 国产精品123区 | 91久久精品一区二区二区 | 日韩电影a | 黄色免费av | 亚洲精品精品 | 在线天堂免费中文字幕视频 | 凹凸日日摸日日碰夜夜 | 亚洲精品大片 | 综合第一页 | 亚洲成av | 一区二区三区精品在线 | 欧美性视频在线播放 | 久久av综合 | 亚洲欧洲日韩 | 日韩手机在线看片 | 91精品国产一区二区三区蜜臀 | 欧美a在线观看 | 亚洲a视频 | av在线天堂| 日日人人| 久久大陆| 自拍偷拍一区二区三区 | 91精品国产综合久久福利软件 | 欧美一区二区免费在线 | 久久久久久久av | 久久精品手机视频 | 成人依人 | 午夜精品久久久久久久久久久久久 | 国产有码| 免费日本视频 |