开发者

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

开发者 https://www.devze.com 2023-03-06 08:08 出处:网络
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?

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))
            {
   开发者_Python百科             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 static Object.Equals method. You want:

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

Incidentally, that method looks something like this:

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's now safe to call objA.Equals
    return objA.Equals(objB);
} 

Even if that method didn't exist, you could still write your assignment this way:

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

That uses a different lambda depending on whether x.Parent is null. If it's null, it just has to look for objects whose Parent is null. If not, it's always safe to call x.Parent.Equals and uses a lambda that does so.


You can use object.Equals instead.

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

object.Equals will use the first parameters Equal override so long as both parameters are not null.

0

精彩评论

暂无评论...
验证码 换一张
取 消