是否可以编写此代码,以便在与也具有 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/