Count items existing in 2 Lists

JulyOrdinary picture JulyOrdinary · Aug 5, 2013 · Viewed 7.2k times · Source

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
    }
}

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

Answer

It&#39;sNotALie. picture It'sNotALie. · Aug 5, 2013
B.Intersect(A).Count(); //should do the job