Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

c#

.net

linq

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?

like image 599
dotnetnoob Avatar asked Jul 02 '13 12:07

dotnetnoob


People also ask

Is LINQ more efficient than foreach?

LINQ syntax is typically less efficient than a foreach loop. It's good to be aware of any performance tradeoff that might occur when you use LINQ to improve the readability of your code.

Which one is faster for or foreach in C#?

The forloop is faster than the foreach loop if the array must only be accessed once per iteration.

Is LINQ faster than for loop?

No, LINQ iterators are not and will never be faster than foreach .

What is difference between for loop and foreach loop in C#?

Difference between for loop and foreach loop:for loop executes a statement or a block of statement until the given condition is false. Whereas foreach loop executes a statement or a block of statements for each element present in the array and there is no need to define the minimum or maximum limit.


2 Answers

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.

like image 60
Claudio Redi Avatar answered Oct 13 '22 10:10

Claudio Redi


If this is linq 2 sql, never do that.

You cause an extra round trip.

Also if you have any other type of IEnumerable, you should avoid that. .net does some tricks for underlying list, but you shouldn't rely on those.

like image 28
eglasius Avatar answered Oct 13 '22 10:10

eglasius