How to have an Iterator for a Dictionary?

I have a class that uses a dictionary to store some data.

But I want to hide this implementation detail from the outside in order to iterate all my data that I would like to send to the iterator for my class

How can i do this?

+4
source share
4 answers
public IEnumerable<KeyValuePair<int, string>> Foo() { var implementationDetail = new Dictionary<int, string> { { 1, "foo" }, { 2, "bar" }, }; return implementationDetail; } 
+4
source

You can call Dictinary.GetEnumerator() , which returns an enumerator.

+2
source

You can return _dict.getEnumerator() , but this will cause KeyValuePair elements to appear. You can also return an IDictionary .

So you probably want _dict.Keys.getEnumerator() and / or the same thing for values.

But returning the counter is odd, it's much better to return: _dict.Keys as IEnumerable<KeyType>

+1
source

To iterate over a dictionary, you can use:

Dictionary.GetEnumerator , which returns KeyValuePairs.

Dictionary.Keys , which returns a KeyCollection.

Dictionary.Values that returns a ValueCollection.

If for some reason you need to hide the dictionary, you can use dictionary words and a dictionary. The values ​​in the array / list you want.

+1
source

Source: https://habr.com/ru/post/1391829/


All Articles