Find and change the value of first element in list that meets a requirement, do something else if not found

This seems to be ridiculously easy, but I just can't seem to find a way to do it. Basically the title, I want to find the first item in my list that meets a requirement, and modify the value of that found item, and if none of the items in that list meets it, then do something else.

I was using a foreach loop to this, but it is definitely not the fastest way.

foreach (CustomClass foo in bar)
{
    if (!foo.Value)
    {
         foo.Value = true;
         currentCount++;
         break;
    }
}

I then tried to use List.First() and catching the exception when it can't find the value, but that is far slower, and I'm looking for performance.

EDIT: Never mind about what is below, I found how to make first or default work, but is there a faster way to do this multiple times than the foreach method? Thanks


So I tried FirstOrDefault, but I keep getting null reference exception

if (bar.FirstOrDefault(c => c.Value == false).Equals(null))
{
    break;
}
else
{
    thePicture.FirstOrDefault(c => c.Value == false).Value = true;
    currentCount++;
}

Anyone know how to make the first or default work? Or is there any other way to do this faster than the foreach method. (This will be ran in another loop a lot of times) Thanks!

Jon Skeet
people
quotationmark

FirstOrDefault will return a null reference if no element is found - assuming the element type is a reference type. Instead of calling Equals on the result, just use ==... and don't call it twice:

var first = bar.FirstOrDefault(c => !c.Value);
if (first == null)
{
    ...
}
else
{
    // Use first, I suspect.
    // (You don't in the sample code, but...)
}

Note that this won't be faster than an appropriate foreach loop, but it can be more readable.

people

See more on this question at Stackoverflow