DavidB
DavidB

Reputation: 2596

Comparing two lists to get objects that appear in both

I have two lists of the same class, and want to generate a count of objects that appear in both lists.

Dim repeatingMentions As Integer 
repeatingMentions =currentMentions.Where(Function(m) previousMentions.Contains(m)).Count

Debugging I can see that the two lists contain objects with exactly the same property values, is this enough to satisfy contains because the count is coming back as 0.

Upvotes: 2

Views: 5818

Answers (4)

Sriram Sakthivel
Sriram Sakthivel

Reputation: 73502

Use Intersect method from Linq to find the intersection in two sequences, then call Count method to count it.

repeatingMentions = currentMentions.Intersect(previousMentions).Count()

Note that above method compares the instances by references by default. If you want custom implementation you need to use this overload of Intersect which takes IEqualityComparer as parameter.

Upvotes: 2

fnupp
fnupp

Reputation: 188

You can use the intersect extension method for this.(You might have to reference it by referencing the namespace System.Linq)

An Example with a list of strings.

List<string> a = new List<string>();
List<string> b = new List<string>();

var result =  a.Intersect(b);

Depending on your object you should implement a IEqualityComparer and pass it to the intersect method to correctly compare the object (implements Equals and getHash)

Upvotes: 0

user3972104
user3972104

Reputation:

Let a() and b() are two integer arrays, you can select the count of common elements in both the arrays using the code below. same as in the case of string arrays also.

    Dim a As Integer() = {1, 5, 2, 3, 6, 4, 7, 89, 5, 8}
    Dim b As Integer() = {4, 78, 85, 2, 2, 3, 1, 4, 8}
    Dim count As Integer = a.Intersect(b).Count

Upvotes: 0

Tim Schmelter
Tim Schmelter

Reputation: 460340

You have to override Equals + GetHashCode or provide a custom IEqualityComparer(Of YourClassName) to make this work with Contains. Or you have to use Any:

repeatingMentions  = currentMentions.
    Count(Function(m) previousMentions.
        Any(Function(p) m.PropertyName = p.PropertyName))

or you could join both lists via Enumerable.Join:

Dim inBoth = From currMent In currentMentions
             Join prevMent In previousMentions
             On currMent.PropertyName Equals prevMent.PropertyName
repeatingMentions = inBoth.Count()

Upvotes: 4

Related Questions