Reputation: 1729
Is there any benefit of calling .Any() on an enumeration right before enumerating it ? For example (granted that list is an IEnumerable):
if(list != null && list.Any())
{
foreach(var item in list)
{
// do stuff
}
}
I suspect that it has none, but I'd rather be sure.
Upvotes: 1
Views: 296
Reputation: 14972
No not really. If the list is empty your foreach loop will simply not iterate.
if(list != null)
{
foreach(var item in list)
{
// do stuff
}
}
Upvotes: 0
Reputation: 5151
No, no real benefit.
If the list is not null, but empty, foreach will be fine (i.e. it will not throw an exception and it won't enumerate over an empty list). Doing the null check should be enough.
Upvotes: 0
Reputation: 301337
There is no real benefit, but possible downside to calling Any
here as you could be enumerating twice.
A null check should be enough. The foreach will take care of the rest for you.
Upvotes: 2