Network Security Internet Technology Development Database Servers Mobile Phone Android Software Apple Software Computer Software News IT Information

In addition to Weibo, there is also WeChat

Please pay attention

WeChat public account

Shulou

What are the ways to use Dictionary traversal

2025-02-25 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >

Share

Shulou(Shulou.com)06/02 Report--

This article mainly explains "what is the use of Dictionary traversal", interested friends may wish to have a look. The method introduced in this paper is simple, fast and practical. Next let the editor to take you to learn "what is the use of Dictionary traversal" bar!

Use foreach to traverse

To facilitate the demonstration, let's start with a piece of test code:

Var dict = new Dictionary () {[10] = "A10", [20] = "A20", [30] = "A30", [40] = "A40", [50] = "A50"}

1. Direct foreach dict

If you want to speak in terms of percentage, it is estimated that 50% + of the partners use this way. Why is it simple and rude? if there is nothing else to say, go directly to the code:

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

The item here is packaged in KeyValuePair during the MoveNext process. If you don't believe it, take a look at the source code:

Public bool MoveNext () {while ((uint) _ index

< (uint)_dictionary._count) { ref Entry reference = ref _dictionary._entries[_index++]; if (reference.next >

=-1) {_ current = new KeyValuePair (reference.key, reference.value); return true;}}

2. Deconstructing with KeyPairValue in foreach

You have just seen that item is of type KeyValuePair, but netcore has enhanced KeyValuePair by adding a Deconstruct function to deconstruct KeyValuePair, as follows:

Public readonly struct KeyValuePair {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;}}

With this deconstructor, you can directly get the key,value instead of the wrapped KeyValuePair during the traversal, which is not possible in netframework. The implementation code is as follows:

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

3. Foreach keys

In the previous examples, you can foreach the dict directly. In fact, you can also traverse the dict.keys through foreach, and then read the dict through the traversed key. The code is as follows:

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

Speaking of which, I do not know if you have a subconscious, that is, dict can only be traversed through foreach, is this the truth? To find the answer, look back at how foreach traverses.

Public struct Enumerator: IEnumerator, 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 (reference.key, reference.value); return true;}} _ index = _ dictionary._count + 1; _ current = default (KeyValuePair); return false;}}

If you take a closer look at this while loop, you should understand that, in essence, it also traverses the entries array, and the bottom layer uses while. Can I replace it with for and loop dict? Haha, it's just an imitation.

Use for to traverse

In order to simulate the code in MoveNext, the key point is this statement: ref Entry reference = ref _ dictionary._ entries [_ index++]; in fact, it is very simple. The content of the _ entries array can be extracted using the ElementAt method of Linq, isn't it? the modified code is as follows:

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(this IEnumerable source, int index) { IList list = source as IList; if (list != null) { return list[index]; } if (index >

= 0) {using (IEnumerator enumerator = source.GetEnumerator ()) {while (enumerator.MoveNext ()) {if (index = = 0) {return enumerator.Current;} index-- }} at this point, I believe you have a deeper understanding of "what is the use of Dictionary traversal". You might as well do it in practice. Here is the website, more related content can enter the relevant channels to inquire, follow us, continue to learn!

Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.

Views: 0

*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.

Share To

Development

Wechat

© 2024 shulou.com SLNews company. All rights reserved.

12
Report