LINQ itself doesn't contain anything for this - I'd would use a normal foreach
loop:
foreach (var value in objects.Select(x => x.someProperty)
.Where(y => y != null))
{
SomeFunction(value);
}
Or if you want a query expression version:
var query = from obj in objects
let value = obj.SomeProperty
where value != null
select value;
foreach (var value in query)
{
SomeFunction(value);
}
(I prefer the first version, personally.)
Note that I've performed the selection before the filtering to avoid calling the property twice unnecessarily. It's not for performance reasons so much as I didn't like the redundancy :)
While you can use ToList()
and call ForEach()
on that, I prefer to use a straight foreach
loop, as per Eric's explanation. Basically SomeFunction
must incur a side-effect to be useful, and LINQ is designed with side-effect-free functions in mind.