Search code examples
c#linq

LINQ query to select based on property


IEnumerable<MyClass> objects = ...
foreach(MyClass obj in objects)
{
  if(obj.someProperty != null)
    SomeFunction(obj.someProperty);
}

I get the feeling I can write a smug LINQ version using a lambda but all my C# experience is 'classical' i.e more Java-like and all this Linq stuff confuses me.

What would it look like, and is it worth doing, or is this kind of Linq usage just seen as showing off "look I know Linq!"


Solution

  • You can move the if statement into a Where clause of Linq:

    IEnumerable<MyClass> objects = ...
    foreach(MyClass obj in objects.Where(obj => obj.someProperty != null)
    {
        SomeFunction(obj.someProperty);
    }
    

    Going further, you can use List's ForEach method:

    IEnumerable<MyClass> objects = ...
    objects.Where(obj => obj.someProperty != null).ToList()
        .ForEach(obj => SomeFunction(obj.someProperty));
    

    That's making the code slightly harder to read, though. Usually I stick with the typical foreach statement versus List's ForEach, but it's entirely up to you.