Is it possible to write this code so that items in a list with a parent property of null are returned compared to an object (x) that also has a parent of zero?
MyObject obj = objList.FirstOrDefault(o => n.Parent.Equals(x.Parent));
Assuming that the Equals method is correctly overridden, this does not happen if objList has an element with a zero parent - with a “reference to an object not installed in the object instance”. an exception.
I would suggest that this is because if n.Parent is null, you cannot call its Equal method.
Anyway, I currently used 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 works, it is not very elegant.
source
share