计算 2 个列表中存在的项目 [英] Count items existing in 2 Lists

查看:20
本文介绍了计算 2 个列表中存在的项目的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有两个 int 类型 ListList AList B.我想检查List B中有多少List A的项目.我能够做到这一点,但是当我试图避免 foreach 时,什么是有效的方法,因为优化是我代码中的主要目标.

I have two int type List like List A and List B. I want to check how many items of List A are there in List B. I am able to do this, but what can be an efficient way as I am trying to avoid foreach, as optimization is a prime target in my code.

List<int> A = new List<int>;
List<int> B = new List<int>;
// Some logic....item added in both lists. Then

foreach(var item in A)
{
    if (B.Contains(item))
    {
        // Subtract number of duplicates
    }
}

我尝试使用 IntersectAny,但这会返回 bool,因此我无法完全应用它们.

I tried using Intersect and Any, but that returns bool so I'm not able to apply them completely.

推荐答案

B.Intersect(A).Count(); //should do the job

这篇关于计算 2 个列表中存在的项目的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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