我有什么看起来像一个常见的问题/模式。两个集合相同的对象。该对象具有许多属性和其中的一些嵌套对象。 Car有一个名为id的属性,它是唯一的标识符。
i have what seems like a common problem / pattern. two collections of the same object. The object has a number of properties and some nested objects within it. Car has a property called id which is the unique identifier.
我想找到LINQ的方式来做一个diff,其中包括:
I want to find the LINQ way to do a diff, which includes:
推荐答案
您可以使用 Enumerable.Except()方法,使用比较器(默认值或您提供的值)来评估哪些对象两个序列或只有一个:
You can use the Enumerable.Except() method. This uses a comparer (either a default or one you supply) to evaluate which objects are in both sequences or just one:
var sequenceA = new[] { "a", "e", "i", "o", "u" }; var sequenceB = new[] { "a", "b", "c" }; var sequenceDiff = sequenceA.Except( sequenceB );如果要执行两个序列的完全析取 (BA),您必须使用:
If you want to perform a complete disjunction of both sequences (A-B) union (B-A), you would have to use:
var sequenceDiff = sequenceA.Except( sequenceB ).Union( sequenceB.Except( sequenceA ) );如果你有一个复杂的类型,你可以写一个 IComparer< T&
If you have a complex type, you can write an IComparer<T> for your type T and use the overload that accepts the comparer.
对于您的问题的第二部分,您需要滚动您自己的实现来报告类型的哪些属性是不同的..没有内置到.NET BCL直接。您必须决定此报告将采用什么形式?你如何识别和表达复杂类型的差异?你可以使用反射这个...但如果你只处理一个类型,我会避免,并写一个专门的差异实用程序只为它。如果你要支持一系列的类型,反射可能会更有意义。
For the second part of your question, you would need to roll your own implementation to report which properties of a type are different .. there's nothing built into the .NET BCL directly. You have to decide what form this reporting would take? How would you identify and express differences in a complex type? You could certainly use reflection for this ... but if you're only dealing with a single type I would avoid that, and write a specialized differencing utility just for it. If yo're going to support a borad range of types, then reflection may make more sense.
更多推荐
比较两个集合
发布评论