+ 1

Why do i need .ToArray inside foreach in this program?, and what is clearly the use of it????

https://code.sololearn.com/c7d0L2Pq1Pfd/?ref=app

3rd Jun 2021, 9:10 AM
Xenon
Xenon - avatar
5 Answers
+ 1
The response is a little more complicated. The exception depends from implementation of Dictionary<TKey, TValue>.KeyCollection enumerator, it perform a check that control if the whole dictionary has changed and not only the KeyCollection, so when you change the value of first entry the check in the MoveNext method of enumerator fails and it throw an exception. If you remove the assignment in the foreach you can notice that it works without the .ToArray(). The reason why it works with .ToArray() is because you create a new collection that is not related directly to the dictionary. And remember that the foreach statement can enumerate any type that implements IEnumerable. I hope I was clear.
4th Jun 2021, 2:05 AM
Eymerich
+ 3
In the C# tutorial under Arrays and Strings, lesson 43.1 is a statement indicating that foreach is used to easily iterate through an Array. coffee.Keys.ToArray() is taking the keys of your dictionary (coffee), and placing them into an Array that may now be iterated upon by your foreach function.
3rd Jun 2021, 10:14 AM
Rik Wittkopp
Rik Wittkopp - avatar
+ 3
Thanks it makes sense now
3rd Jun 2021, 10:16 AM
Xenon
Xenon - avatar
+ 2
You can see foreach like a function that accept an array as parameter (IEnumerable). In your case, you are passing the return of ToArray() directly to this function. You may also assign the result of ToArray to a variable and invoke the foreach on that variable. But if you don't need to access to the array after the foreach you can avoid to declare the variable. Obviously the array is created in the ToArray() method and returned as result.
4th Jun 2021, 10:10 PM
Eymerich
0
I just noticed that .ToArray is used to put a List/Dictionary<K, V> in an array, so i wondered how can it access the new created array even in this code doesnt declare an array?
4th Jun 2021, 2:39 AM
Xenon
Xenon - avatar