Find the first item in a list which gives a value, and return the value

112 Views Asked by At

How could the following iterative algorithm be rewritten using Linq?

int GetMatchingValue(List<Thing> things)
{
 foreach(Thing t in things)
 {
  var value = thing.ComplicatedCalculation();
  if(value > 0)
   return value;
 }
}

It's easy to find which Thing we want with LINQ:

var thing = things.FirstOrDefault(t => t.ComplicatedCalculation() > 0);

But then you have to do the check again to see which value to return:

return thing?.ComplicatedCalculation() ?? 0;

Is there a way to return the calculated value using LINQ without having to do it twice? Or is this a case where iterating the list is the simplest/cleanest solution? I would welcome a solution employing MoreLINQ also.

1

There are 1 best solutions below

2
NetMage On

Use LINQ to first transform to the value you care about and find the one you want to return:

int GetMatchingValue(List<Thing> things)
    => things.Select(t => t.ComplicatedCalculation()).FirstOrDefault(v => v > 0);