查找两个列表之间是否有相交的最快方法是什么? [英] What is the quickest method to find is there intersect between two list?

查看:34
本文介绍了查找两个列表之间是否有相交的最快方法是什么?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我已经编写了一个代码来检查两个列表之间的交集.我只需要有路口.有没有一种更快的方法.

I have written a code to check intersection between two list. I need only is there intersection. Is there a quicker way for it.

L,L2 are List<int>

bool working = true;

bool ok=false;
for (int k = 0; k<L.Count && working;k++) {
   if (L2.Any (a => a == L[k])) {
      ok=true;//There is an integer in L and   L2
      working=false;
   }
}

推荐答案

不确定我是否忽略了某些内容,但通常您会使用

Not sure if i have overlooked something, but normally you'd use Intersect+Any:

bool intersects = L.Intersect(L2).Any();

如果列表中的类型像大多数.NET类一样覆盖 Equals GetHashCode ,则此方法有效.如果您使用自己的笔记本电脑,则应记住这一点,否则只会比较引用.

This works if the type in the list overrides Equals and GetHashCode like most .NET classes do. If you use your own you should remember that, otherwise only references are compared.

这篇关于查找两个列表之间是否有相交的最快方法是什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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