使用linq比较2个数组 [英] Compare 2 arrays using linq

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

问题描述

有人能告诉我如何使用LINQ到C#比较两个数组并将匹配值存储在一个数组中并在一个数组中存储不匹配的值吗?在此先感谢。

can anyone tell me how to compare two arrays using LINQ through C# and store the matching values in one array and unmatching values in one array? Thanks in advance.

推荐答案

不幸的是,比较会要求所讨论的值具有可比性。这通常通过实现IEqualityComparer< T>来处理,以进行相等性比较。基元和值类型将按值进行比较,但ref类型将默认比较
对象引用。但假设您的类型有IEqualityComparer,那么您可以使用

除了
以获得差异。 Except文档中有一个比较2个Product数组作为示例实现的示例。

Unfortunately comparison would require that the values in question be comparable. This is generally handled by implementing IEqualityComparer<T>, for equality comparison. Primitives and value types would compare by value but ref types will simply compare object references by default. But assuming you have an IEqualityComparer for your type then you can use Except to get the differences. The Except documentation has an example of comparing 2 Product arrays as an example implementation.

要获得匹配,请考虑使用
相交
,它只返回两者中的值。除了使用Intersect之外,它具有相同的示例。

To get the matches then consider using Intersect which will return only the values that are in both. It has the same example except using Intersect.


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

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