I have a record struct, similar to as:
public readonly record struct Something(string Prop1, string Prop2);
And a method that receives List<Something> theList
.
In that method I have:
Something? x = theList.FirstOrDefault(i => i.Prop1 == "..." && i.Prop2 == "....");
So, because I declared "x" as Something? x
(nullable) I was expecting x
to be null if it wasn't found, since I'm using .FirstOrDefault(...)
.
However, I always get x - it's not null even if the conditions aren't met.
Okay, so I then check x.HasValue
and expected this to be false as I know the item in question doesn't exist. However, this returned true
which suggests I've found the item? But no, when I inspect x.Value.Prop1 then it's value is null
, and same for x.Value.Prop2
.
Wasn't expecting this... (using .NET 7)
What's the best way to find if an record struct exists, and only if it exists, take it?
I thought of using .Any(i => i.Prop1 == "..." && i.Prop2 == "....")
but it will have to search through my entire list first and if it returns true then I'd have to do a second pass through the list to retrieve it.