dotnetnoob
dotnetnoob

Reputation: 11350

Is there any benefit to calling .Any() before .ForEach() when using 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?

Upvotes: 6

Views: 1231

Answers (3)

Claudio Redi
Claudio Redi

Reputation: 68440

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.

Upvotes: 16

eglasius
eglasius

Reputation: 36035

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.

Upvotes: 4

Captain Skyhawk
Captain Skyhawk

Reputation: 3500

There's really no point in calling Any before the Where. If no results come back from the Where query, you will never enter the for loop.

Calling the Any before the where will actually end up hurting performance because you're doing two queries.

Upvotes: 0

Related Questions