简体   繁体   English

如何使用C#比较两个列表?

[英]how to compare two lists using C#?

I have two lists how can I check if list1 has some items that are from list2 我有两个列表如何检查list1是否有一些来自list2的项目

for ie i have: 因为我有:

list1 = ["car","424", "fwe"]
list2 = ["car", "cat"]

maybe something like this: 也许是这样的:

if list1 has elements from  list2

then return true 然后返回true

您可以使用LINQ IntersectExcept功能Except

您可以使用与任何相交:

list1.Intersect(list2).Any()

The best solution really depends on the specifics of your situation. 最好的解决方案实际上取决于您的具体情况。

For instance, you could compare each pair of elements, which would be a very straightforward implementation. 例如,您可以比较每对元素,这将是一个非常简单的实现。 However, this isn't particularly efficient if the lists are long. 但是,如果列表很长,这不是特别有效。

A second option would be to add all the elements of one list to a HashSet, and then try to add all the elements of the second list. 第二个选项是将一个列表的所有元素添加到HashSet,然后尝试添加第二个列表的所有元素。 If there is an element in common, the HashSet Add() method will return false when you try to add the duplicate. 如果存在共同的元素,则在尝试添加副本时,HashSet Add()方法将返回false。 This will be faster for large lists, but requires additional memory, and may produce less readable code. 这对于大型列表来说会更快,但需要额外的内存,并且可能会产生可读性较低的代码。

另一种可能的方案

list1.Any(e => list2.Contains(e));

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM