比较两个集合 [英] Comparing two collections

查看:98
本文介绍了比较两个集合的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有什么看起来像一个常见的问题/模式。两个集合相同的对象。该对象具有许多属性和其中的一些嵌套对象。 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:


  1. 一个集合中的项目,而不是另一个集合中的项目(反之亦然)

  2. 对于匹配的项目,是否有任何更改(我只关心可设置的属性,我会使用反射吗?)


推荐答案

您可以使用 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.

这篇关于比较两个集合的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆