Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Resharper's example code for explaining "Possible multiple enumeration of IEnumerable"

Sometimes Resharper warns about:

Possible multiple enumeration of IEnumerable

There's an SO question on how to handle this issue, and the ReSharper site also explains things here. It has some sample code that tells you to do this instead:

IEnumerable<string> names = GetNames().ToList(); 

My question is about this specific suggestion: won't this still result in enumerating through the collection twice in the 2 for-each loops?

like image 657
user2250250 Avatar asked Nov 21 '13 18:11

user2250250


People also ask

What is possible multiple enumeration of IEnumerable?

Deferred Danger. One of the many useful warnings in ReSharper is “Possible multiple enumeration of IEnumerable“. If you enumerate an enumerable more than once, ReSharper detects that and warns you about it. Although this warning may seem pointless at first, there are two good reasons to pay attention to it.

Why is multiple enumerations bad?

Enumerating an enumerable can be very expensive. For example, an enumerable might be backed by a database. Re-enumerating may force you to wait another network round trip. You don't want to pay that cost twice.


2 Answers

GetNames() returns an IEnumerable. So if you store that result:

IEnumerable foo = GetNames(); 

Then every time you enumerate foo, the GetNames() method is called again (not literally, I can't find a link that properly explains the details, but see IEnumerable.GetEnumerator()).

Resharper sees this, and suggests you to store the result of enumerating GetNames() in a local variable, for example by materializing it in a list:

IEnumerable fooEnumerated = GetNames().ToList(); 

This will make sure that the GetNames() result is only enumerated once, as long as you refer to fooEnumerated.

This does matter because you usually want to enumerate only once, for example when GetNames() performs a (slow) database call.

Because you materialized the results in a list, it doesn't matter anymore that you enumerate fooEnumerated twice; you'll be iterating over an in-memory list twice.

like image 52
CodeCaster Avatar answered Sep 19 '22 16:09

CodeCaster


I found this to have the best and easiest way to understand multiple enumerations.

C# LINQ: Possible Multiple Enumeration of IEnumerable

https://helloacm.com/c-linq-possible-multiple-enumeration-of-ienumerable-resharper/

like image 44
Just R Avatar answered Sep 18 '22 16:09

Just R