有效识别第一组中的任何项目是否与第二组中的任何项目匹配

发布于 2024-10-04 05:36:53 字数 334 浏览 0 评论 0原文

我有两个代表字符串列表的 IEnumerable。我想看看第一组中的任何元素是否与第二组中的任何元素匹配。目前我有一些看起来像这样的东西:

firstSet.Intersect(secondSet).Count() > 0

但是,在我看来效率相当低,因为它会生成匹配元素的列表,然后对它们进行全部计数。然后我可以测试计数是否大于零。我不关心哪个匹配、多少个匹配,只关心两个集合中的任何元素匹配。我缺少类似 firstSet.AnyMatch(secondSet) 的内容吗?

有没有更有效的方式来表达?

I have two IEnumerable<string> that represent lists of strings. I want to see if any element in the first set matches any element in the second set. At the moment I have something that looks like this:

firstSet.Intersect(secondSet).Count() > 0

However, it seems to me to be rather inefficient because it will produce a list of the elements that match, then count them all. I can then test to see if the count is greater than zero. I don't care about which match, how many match, just that any element in the two sets match. Is there anything like firstSet.AnyMatch(secondSet) that I'm missing?

Is there a more efficient way to express that?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

还在原地等你 2024-10-11 05:36:53

使用 Any 代替:

if (firstSet.Intersect(secondSet).Any())

我相信这将首先构建第二个集合的哈希集(完整),然后迭代第一个集合,直到找到匹配或运行没有要测试的元素。在确定放置 firstSetsecondSet 的方式时,您可能希望牢记这一点。

编辑:只是为了重复评论中已有的内容...如果您知道(例如)firstSet 是一个 HashSet 那么您应该转换为它并使用 < a href="http://msdn.microsoft.com/en-us/library/bb355623%28v=VS.90%29.aspx" rel="nofollow">重叠 :

HashSet<string> firstHashSet = (HashSet<string>) firstSet;
if (firstHashSet.Overlaps(secondSet))
{
    ...
}

Use Any instead:

if (firstSet.Intersect(secondSet).Any())

I believe this will build of hash set of the second collection first (in its entirety) and then iterate over the first set until it finds a match or runs out of elements to test. You may wish to bear this in mind when working out which way round to put firstSet and secondSet.

EDIT: Just to repeat what's already in a comment... if you know that (say) firstSet is a HashSet<string> then you should cast to it and use Overlaps:

HashSet<string> firstHashSet = (HashSet<string>) firstSet;
if (firstHashSet.Overlaps(secondSet))
{
    ...
}
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文