小编Dav*_*dit的帖子

使用具有偶然空属性的LINQ SequenceEqual扩展方法

我正在编写一个简单的控制台应用程序来比较自定义类对象的两个实例.对于每个属性,我在控制台窗口中写入True或False,以显示每个对象的属性是否匹配.

某些属性(如ProductLines(List属性))在一个或两个对象中可能为null,或者两者都不为.这对使用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));
}
Run Code Online (Sandbox Code Playgroud)

.net c# linq

3
推荐指数
2
解决办法
1107
查看次数

标签 统计

.net ×1

c# ×1

linq ×1