如何查找列表中的元素是否在另一个列表中? [英] How to find if an element of a list is in another list?

查看:62
本文介绍了如何查找列表中的元素是否在另一个列表中?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想知道在第二个列表中是否可以找到第一个列表中的至少一个元素.

I want to know if at least one element in a first list can be found in a second list.

我可以看到两种方法.假设我们的列表是:

I can see two ways to do it. Let's say our lists are:

List<string> list1 = new[] { "A", "C", "F", "H", "I" };
List<string> list2 = new[] { "B", "D", "F", "G", "I" };

第一种方法使用循环:

bool isFound = false;
foreach (item1 in list1)
{
    if (list2.Contains(item1))
    {
        isFound = true;
        break;
    }
}

第二个直接使用Linq:

The second one uses Linq directly:

bool isFound = list1.Intersect(list2).Any();

第一个很长的时间写,不是很直接/容易阅读.第二个简短明了,但是性能会很低,尤其是在大型列表上.

The first one is long to write and not very straightforward/easy-to-read. The second one is short and clear, but performances will be low, especially on large lists.

什么可能是一种优雅的方式?

What may be an elegant way to do it?

推荐答案

第二个在大型列表上的性能比第一个更好. Intersect在检查另一个列表的成员资格之前,将一个列表的元素放入哈希表.

The second one has better performance on large lists than the first one. Intersect puts the elements of one list into a hash table before checking the other list's elements for membership.

这篇关于如何查找列表中的元素是否在另一个列表中?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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