Is it possible for the Enumerable.FirstOrDefault method to deal with null parameters

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.

+3
source share
2 answers

FirstOrDefault, , Object.Equals. :

MyObject obj = objList.FirstOrDefault(o => Object.Equals(o.Parent, x.Parent));

, :

public static bool Equals(Object objA, Object objB) 
{
    // handle situation where both objects are null or both the same reference
    if (objA == objB)
        return true;
    // both are not null, so if any is null they can't be equal
    if (objA == null || objB == null)
        return false; 
    // nulls are already handled, so it now safe to call objA.Equals
    return objA.Equals(objB);
} 

, :

MyObject obj = objList.FirstOrDefault(x.Parent == null ?
    o => o.Parent == null :
    o => x.Parent.Equals(o.Parent));

, x.Parent null. , , Parent null. , x.Parent.Equals , .

+7

object.Equals.

MyObject obj = objList.FirstOrDefault(o => object.Equals(n.Parent, x.Parent));

object.Equals Equal, .

+3

All Articles