Enumerable.FirstOrDefault 方法是否可以处理 null 参数
是否可以编写此代码,以便在与父属性为 null 的对象 (x) 进行比较时返回列表中父属性为 null 的项目?
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;
}
因此,虽然它确实有效,但它不是很优雅。
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))
{
match = true;
}
}
}
if (match)
{
obj= existingObj;
break;
}
So while it does work, it's not very elegant.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
这与 FirstOrDefault 无关,但这是一个常见问题,可以通过静态 Object.Equals 方法解决。你想要:
顺便说一句,该方法看起来像这样:
即使该方法不存在,你仍然可以这样编写你的作业:
根据
x.Parent
是否为 null 使用不同的 lambda 。如果为 null,则只需查找Parent
为 null 的对象。如果没有,调用 x.Parent.Equals 并使用 lambda 始终是安全的。This has nothing to do with
FirstOrDefault
, but it is a common problem that is solved by the staticObject.Equals
method. You want:Incidentally, that method looks something like this:
Even if that method didn't exist, you could still write your assignment this way:
That uses a different lambda depending on whether
x.Parent
is null. If it's null, it just has to look for objects whoseParent
is null. If not, it's always safe to callx.Parent.Equals
and uses a lambda that does so.您可以使用
object.Equals
代替。只要两个参数都不为空,
object.Equals
将使用第一个参数Equal
覆盖。You can use
object.Equals
instead.object.Equals
will use the first parametersEqual
override so long as both parameters are not null.