【发布时间】:2020-11-19 05:28:20
【问题描述】:
我有一个 SampleObject 的相等比较器:
public bool Equals(SampleObject x, SampleObject y)
{
if (x == null)
{
return y == null;
}
if (y == null)
{
return false;
}
if (!string.Equals(x.SomeId, y.SomeId))
{
return false;
}
if (x.EventsList == null)
{
return y.EventsList == null;
}
if (y.EventsList == null)
{
return false;
}
return x.EventsList.OrderBy(e => e)
.SequenceEqual(y.EventsList.OrderBy(e => e));
}
我想知道是否有办法替换字典中的所有 IF 子句?
【问题讨论】:
-
不是答案,而是观察:当 x.EventsList 和 y.EventsList 都为空时,您将它们视为相等 - 但当 x 和 y 都为空时,您将它们视为不相等。你是故意的吗?
-
@MatthewWatson:我不这么认为:如果 x 和 y 都为 null,则 if (x == null) return y == null 将返回 true。莱蒂没有改变问题,不是吗?
-
你确定是指字典吗?它的关键/价值是什么?或者你是否在使用某种机制,你有某种可枚举的规则集,而第一个返回的规则会终止规则的枚举?
-
旁注:请避免
null用于集合,例如EventList;改用空的 -
@GWimpassinger Doh。 :) 当然你是对的。我需要增加我的字体大小...
标签: c# .net linq dictionary if-statement