溫馨提示×

您好,登錄后才能下訂單哦!

密碼登錄×
登錄注冊(cè)×
其他方式登錄
點(diǎn)擊 登錄注冊(cè) 即表示同意《億速云用戶(hù)服務(wù)條款》

c# 實(shí)現(xiàn)遍歷 Dictionary的方法

發(fā)布時(shí)間:2020-10-30 15:02:22 來(lái)源:億速云 閱讀:557 作者:Leah 欄目:開(kāi)發(fā)技術(shù)

c# 實(shí)現(xiàn)遍歷 Dictionary的方法?很多新手對(duì)此不是很清楚,為了幫助大家解決這個(gè)難題,下面小編將為大家詳細(xì)講解,有這方面需求的人可以來(lái)學(xué)習(xí)下,希望你能有所收獲。

1. 直接 foreach dict

如果要拿百分比說(shuō)話(huà),估計(jì)有 50%+ 的小伙伴用這種方式,為啥,簡(jiǎn)單粗暴唄,其他沒(méi)什么好說(shuō)的,直接上代碼:

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

c# 實(shí)現(xiàn)遍歷 Dictionary的方法

這里的 item 是底層在 MoveNext 的過(guò)程中用 KeyValuePair 包裝出來(lái)的,如果你不信的話(huà),看下源碼唄:

	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 類(lèi)型,不過(guò)&#128002;&#128067;的是 netcore 對(duì) KeyValuePair 進(jìn)行了增強(qiáng),增加了 Deconstruct 函數(shù)用來(lái)解構(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è)解構(gòu)函數(shù),你就可以在遍歷的過(guò)程中直接拿到 key,value,而不是包裝的 KeyValuePair,這在 netframework 中可是不行的哈,實(shí)現(xiàn)代碼如下:

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

c# 實(shí)現(xiàn)遍歷 Dictionary的方法

3. foreach keys

前面的例子都是直接對(duì) dict 進(jìn)行 foreach,其實(shí)你還可以對(duì) dict.keys 進(jìn)行 foreach 遍歷,然后通過(guò)遍歷出的 key 對(duì) dict 進(jìn)行類(lèi)索引器讀取,代碼如下:

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

c# 實(shí)現(xiàn)遍歷 Dictionary的方法

仔細(xì)看這個(gè) while 循環(huán),你就應(yīng)該明白,本質(zhì)上它也是對(duì) entries 數(shù)組進(jìn)行遍歷,那底層都用了 while,我是不是可以用 for 來(lái)替換然后循環(huán) dict 呢?哈哈,反正就是模仿唄。

三:使用 for 遍歷

為了把 MoveNext 中的代碼模擬出來(lái),重點(diǎn)在于這條語(yǔ)句: ref Entry reference = ref _dictionary._entries[_index++];, 其實(shí)很簡(jiǎn)單,_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]}");
      }

c# 實(shí)現(xiàn)遍歷 Dictionary的方法

接下來(lái)是不是很好奇這個(gè) ElementAt 擴(kuò)展方法是如何實(shí)現(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--;
        }
      }
    }
  }

看完上述內(nèi)容是否對(duì)您有幫助呢?如果還想對(duì)相關(guān)知識(shí)有進(jìn)一步的了解或閱讀更多相關(guān)文章,請(qǐng)關(guān)注億速云行業(yè)資訊頻道,感謝您對(duì)億速云的支持。

向AI問(wèn)一下細(xì)節(jié)

免責(zé)聲明:本站發(fā)布的內(nèi)容(圖片、視頻和文字)以原創(chuàng)、轉(zhuǎn)載和分享為主,文章觀(guān)點(diǎn)不代表本網(wǎng)站立場(chǎng),如果涉及侵權(quán)請(qǐng)聯(lián)系站長(zhǎng)郵箱:is@yisu.com進(jìn)行舉報(bào),并提供相關(guān)證據(jù),一經(jīng)查實(shí),將立刻刪除涉嫌侵權(quán)內(nèi)容。

AI