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

时间:2014-03-04 07:01:48

标签: c# .net linq

我正在编写一个简单的控制台应用程序,用于比较自定义类对象的两个实例。对于每个属性,我在控制台窗口中写入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));
}

2 个答案:

答案 0 :(得分:5)

您肯定会重复显示Property Match结果。仅显示一次结果。将计算移至单独的方法:

Console.WriteLine("Property Match:{0}", 
  IsMatch(commsA.Last().ProductLines, commsB.Last().ProductLines));

像这样:

public bool IsMatch<T>(IEnumerable<T> a, IEnumerable<T> b)
{
    if (a != null && b != null)
       return a.SequenceEqual(b);

    return (a == null && b == null);
}

答案 1 :(得分:5)

我可能会添加NullRespectingSequenceEqual扩展名方法:

public static class MoreEnumerable
{
    public static bool NullRespectingSequenceEqual<T>(
        this IEnumerable<T> first, IEnumerable<T> second)
    {
        if (first == null && second == null)
        {
            return true;
        }
        if (first == null || second == null)
        {
            return false;
        }
        return first.SequenceEqual(second);
    }
}

或者使用堆叠条件运算符:

public static class MoreEnumerable
{
    public static bool NullRespectingSequenceEqual<T>(
        this IEnumerable<T> first, IEnumerable<T> second)
    {
        return first == null && second == null ? true
             : first == null || second == null ? false
             : first.SequenceEqual(second);
    }
}

然后你可以使用:

Console.WriteLine("Property Match: {0}",
     x.ProductLines.NullRespectingSequenceEqual(y.ProductLines));

(关于您是否应该致电Last的业务略有不同。)

您可以在任何需要的地方重用该扩展方法,就好像它是LINQ to Objects的正常部分一样。 (当然,它不适用于LINQ to SQL等。)