Is there any benefit to calling .Any() before .ForEach() when using linq?

.net, c#, linq

Solution

Unless you have some logic after the `foreach` statement that you want to avoid, that's unnecessary as it will work the same.

When `foreach` iterates over `nodesWithRules` detects that there are no items and exit the loop.

Problem

I have many methods like the one below: ``` void ValidateBuyerRules() { var nodesWithRules = ActiveNodes.Where(x => x.RuleClass.IsNotNullOrEmpty()); **if (!nodesWithRules.Any()) return;** foreach (var ruleClass in nodesWithRules) { // Do something here } } ``` As you can see, I check if nodesWithRules has any items and exit the method before conducting the foreach statement, but is this unecessary code?

Original source