我正在编写一个简单的控制台应用程序,用于比较两个自定义类对象的实例。对于每个属性,我将True或False写入控制台窗口,以显示每个对象的属性是否匹配。
有些属性,如ProductLines(列表属性),在一个或两个对象中可能为空...或者都不为空。这对使用SequenceEqual来比较它们带来了一些问题,因为它不接受空值。 有比我编写的代码更好的方法来比较两个序列属性吗?
// test if either collection property is null.
if (commsA.Last().ProductLines == null || commsB.Last().ProductLines == null)
{
// if both null, return true.
if (commsA.Last().ProductLines == null && commsB.Last().ProductLines == null)
{
Console.WriteLine("Property Match:{0}", true);
}
// else return false.
else
{
Console.WriteLine("Property Match:{0}", false);
}
}
// neither property is null. compare values and return boolean.
else
{
Console.WriteLine("Property Match:{0}",
commsA.Last().ProductLines.SequenceEqual(commsB.Last().ProductLines));
}
commsA.Last()
或commsB.Last()
时,都会执行查询。即使使用 Linq to Objects,这也涉及创建枚举器并执行 Last()。 - Sergey BerezovskiyLast()
的结果。否则,您有每次迭代它的风险。至少这会浪费资源,而您可以将其花费为0。 - abatishchevIList<T>
,则不涉及任何迭代。无论如何,避免仍然是值得的... - Jon Skeetif (first == null) throw Error.ArgumentNull("first")
。你是对的,如果源是IList<T>
,就不会使用Last()
进行枚举(但仍然存在一些开销..)。 - Sergey Berezovskiy