有效识别第一组中的任何项目是否与第二组中的任何项目匹配
我有两个代表字符串列表的 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 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
使用
Any
代替:我相信这将首先构建第二个集合的哈希集(完整),然后迭代第一个集合,直到找到匹配或运行没有要测试的元素。在确定放置
firstSet
和secondSet
的方式时,您可能希望牢记这一点。编辑:只是为了重复评论中已有的内容...如果您知道(例如)
firstSet
是一个HashSet
那么您应该转换为它并使用 < a href="http://msdn.microsoft.com/en-us/library/bb355623%28v=VS.90%29.aspx" rel="nofollow">重叠
:Use
Any
instead: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
andsecondSet
.EDIT: Just to repeat what's already in a comment... if you know that (say)
firstSet
is aHashSet<string>
then you should cast to it and useOverlaps
: