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.
Use LINQ to first transform to the value you care about and find the one you want to return: