Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Possible duplicate enumeration of IEnumerable

Tags:

c#

linq

resharper

I have wrote the following code:

IEnumerable<string> blackListCountriesCodes = 
pair.Criterion.CountriesExceptions.Select(countryItem => countryItem.CountryCode);

IEnumerable<string> whiteListCountriesCodes = 
pair.Criterion.Countries.Select(countryItem => countryItem.CountryCode);

return (!blackListCountriesCodes.Contains(Consts.ALL.ToString()) &&
        !blackListCountriesCodes.Contains(country) &&
        (whiteListCountriesCodes.Contains(Consts.ALL.ToString()) ||
        whiteListCountriesCodes.Contains(country)));

resharper shows me a warning: Possible duplicate enumeration of IEnumerable

What does this mean? Why is this a warning?

like image 545
Elad Benda Avatar asked Dec 20 '12 15:12

Elad Benda


1 Answers

LINQ Queries defer their execution until you do something with the results. In this case, calling Contains() twice on the same collection could cause the results to be enumerated twice which, depending on the query, could cause performance issues.

You can solve this by simply tacking a ToList() call on the end of your query which will force execution of the query and store the results a single time.

like image 109
Justin Niessner Avatar answered Nov 15 '22 07:11

Justin Niessner