比较两个集合

编程入门 行业动态 更新时间:2024-10-25 20:30:01
本文介绍了比较两个集合的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

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

    更多推荐

    比较两个集合

    本文发布于:2023-11-29 00:15:43,感谢您对本站的认可!
    本文链接:https://www.elefans.com/category/jswz/34/1644526.html
    版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
    本文标签:两个

    发布评论

    评论列表 (有 0 条评论)
    草根站长

    >www.elefans.com

    编程频道|电子爱好者 - 技术资讯及电子产品介绍!