c# - Enumerable.FirstOrDefault 方法是否可以处理空参数

标签 c# linq-to-entities

是否可以编写此代码,以便在与也具有 null Parent 的对象 (x) 进行比较时返回列表中具有 null parent 属性的项目?

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

假设“Equals”方法被正确覆盖,如果“objList”中有一个父项为空的项目——“对象引用未设置为对象的实例”,则此方法失败。异常。

我假设会发生这种情况,因为如果 n.Parent 为 null,则您无法调用其 Equal 方法。

无论如何,我目前采用了这种方法:

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;
    }

所以虽然它确实有效,但它不是很优雅。

最佳答案

这与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's 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 使用不同的 lambda。如果它为 null,它只需要查找其 Parent 为 null 的对象。如果不是,调用 x.Parent.Equals 并使用这样做的 lambda 总是安全的。

关于c# - Enumerable.FirstOrDefault 方法是否可以处理空参数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6013822/

相关文章:

c# - Code First 中的正确映射(我闻到了多对多的味道吗?)

c# - 在 Entity Framework 中合并

c# - 与 SQL 更新相比的 LINQ 更新问题。需要帮忙

c# - 如何在 LINQ to Entities 中重用字段过滤器

c# - 从 C++ 启动 C# 应用程序并在该应用程序上执行任务

c# - 制作具有自定义字体的 SVG 文件,供未安装该字体的用户查看

c# - 多个表上的 Linq toEntity 组联接

c# - linq to entities vs linq to objects - 它们是一样的吗?

c# - CLR 垃圾回收方法是否意味着可以安全地抛出循环对象引用?

c# - 如何在 .NET461 中填充 System.Security.Principal.WindowsIdentiy?