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

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!

About Peter Kellner

Peter is a software professional specializing in mobile and web technologies. He has also been a Microsoft MVP since 2007. In addition, he's a multi-course video author at Pluralsight. To read more about Peter Kellner and his experience click here. For information about how Peter Kellner might be able to help you with your project click here.

Follow me:


Follow

Get every new post delivered to your Inbox

Join other followers: