Is LINQifying my code worth accessing a foreach variable in a closure?

浪尽此生 提交于 2019-12-01 21:19:47

You have two different issues here, one LINQ vs foreach, and the other is a different case.

Regarding the ReSharper informing you of "Access to foreach variable in closure..." when the code is LINQified - I just never take my chances, and leave it as a foreach loop. In most cases it is also more readable and maintainable, and really, shortening the code isn't that much of a big deal.

Regarding the second case - you'll need to lose the using statement, since the db object will be disposed too soon. You should close and dispose it in the "old school fashion" INSIDE the RunInTransaction lambda expression, at the end of it.

There's a real difference which will show up in foreach loops, as well as in LINQ queries.

It has to do with the lifetime of the closure (scope) within which a variable is defined (in a foreach loop or in a LINQ expression). In some versions the variable is redefined in each iteration of the loop, and in other occasions its lifetime spans the whole execution of the loop, keeping the old value between iterations. And this can make a big difference in the results, depending on the code.

I can't explain it better than Eric Lippert (which worked for Microsoft for 16 years, developing compilers, including C# compiler):

http://blogs.msdn.com/b/ericlippert/archive/2009/11/12/closing-over-the-loop-variable-considered-harmful.aspx

I have really seen code that behaves in a different way, depending on the traget framework (and thus on the C# version). This must be taken into account.

Most times R# is right, as in this occasion.

You could use the Linq ForEach to remove the open loop.

db.Table<Locations>().Where(l => l.PlatypusId == item).
Where(l=> l.SentTimeUTC >= EarliestToShow).
Where(l=> l.SentTimeUTC <= LatestToShow).
OrderBy(l => l.SentTimeUTC).ToList().
ForEach(q => listLocs.Add(q));
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!