Can this code be written so that items in the list with a parent property of null will be returned when comparing to an object (x) that also has a null Parent?
MyObject obj = objList.FirstOrDefault(o => n.Parent.Equals(x.Parent));
Assuming the “Equals” method is correctly overridden, this fails where there is an item in the “objList” with a null Parent – with an “Object reference not set to an instance of an object.” exception.
I would assume that occurs because if n.Parent is null, you can’t call its Equal method.
Anyway, I currently resorted this this approach:
MyObject obj = null;
foreach (MyObject existingObj in objList)
{
bool match = false;
if (x.Parent == null)
{
if (existingObj.Parent == null)
{
match = true;
}
}
else
{
if (existingObj.Parent != null)
{
if (x.Parent.Equals(existingObj.Parent))
{
match = true;
}
}
}
if (match)
{
obj= existingObj;
break;
}
So while it does work, it’s not very elegant.
This has nothing to do with
FirstOrDefault, but it is a common problem that is solved by the staticObject.Equalsmethod. You want:Incidentally, that method looks something like this:
Even if that method didn’t exist, you could still write your assignment this way:
That uses a different lambda depending on whether
x.Parentis null. If it’s null, it just has to look for objects whoseParentis null. If not, it’s always safe to callx.Parent.Equalsand uses a lambda that does so.