LINQ and “Possible Multiple Enumerations of IEnumerable” Warning / Resharper To the Rescue!

Posted by Peter Kellner on July 29, 2012 · 3 mins read

In the most recent version of Resharper 7 from JetBrains, the brilliant team has gone one step above and beyond.  Not only do they show this error which can be quite tricky to both understand and fix, but they now go one step further and offer a fix.

For example, look at the below code:

var emailDetailInfos = new List<EmailDetailInfo>();
using (var db = new SiteDB())
{
foreach (var emailDetailId in emailDetailIds)
{
// first get details about this particular email
var emailDetail = db.EmailDetails.FirstOrDefault(a => a.Id == emailDetailId);
if (emailDetail != null)
{
// get all the Details associated including the htmlbody if there is one (that is, images and body)
var details = (from ed in db.EmailDetails
join det in db.Details on ed.Id equals det.EmailDetailId
where emailDetailIds.Contains(ed.Id)
select det).ToList();

 

emailDetailIds is actually passed in as a IEnumerable<long> which means that each time I use it, it may be enumerated again. This is a fairly straight forward example as well as the fix, but let’s see what happens when you just ask Resharper to fix it.  You get:

 

var emailDetailInfos = new List<EmailDetailInfo>();
using (var db = new SiteDB())
{
var detailIds = emailDetailIds as List<long> ?? emailDetailIds.ToList();

This simply does the enumeration once, stores it in a static list and we are done.

Very nice!