Search code examples
vb.netlistvisual-studioobjectcontains

VB.NET - List.Contains always returns false when it should be true


I am more of a C# developer, and I am stuck on trying to implement something on my visual basic code; TL;DR is I have a database table which holds all the IDs of Employees that have gone through a process. I want to be able to get those into a list, and see if any of the current members going through this process exist on this list, and if they do remove those members so they don't get reprocessed. The database table returns an object called of type "ProcessedTermedMember" which is a custom object with three string propertys (ID, FirstName, LastName)

I basically have this code here, which is returning false... I know that it is looking to see the Reference is equal by default with contains, so it would only be true when it is the exact same object, vs an object where all properties are the same. How can I override this?

Here is my code:

            Dim termedMembers = (From ec In db.ECs
                                 Where ec.AccountTypeCode = "WCS"
                                 Where ec.AccountStatus = 5
                                 Select ec).ToList()

Dim processedTermMembers = (From p In db.ProcessedTermedMembers
                                        Select p).ToList()

            For Each member In termedMembers
                Dim term As ProcessedTermedMember = New ProcessedTermedMember With {.EmployeeID = member.EmployeeID, .FirstName = member.EmployeeFirstName, .LastName = member.EmployeeLastName}

                If processedTermMembers.Contains(term) Then
                    termedMembers.Remove(member)
                End If
            Next

This 'If Then' statement in the loop always returns "false" how can I get it to return true if all properties in the "term" variable are equal to the properties of one of the list items in "processedTermMembers"?

Any help would be greatly appreciated.


Solution

  • This won't work for a couple of reasons, but namely because you are attempting to modify a collection inside of a For/Each loop.

    The simplest solution would be to move the declaration of termedMembers to after the declaration of processedTermMembers and to add an additional where clause to termedMembers:

    Dim processedTermMembers = (From p In db.ProcessedTermedMembers
                                Select p).ToList()
    
    Dim termedMembers = (From ec In db.ECs
                         Where ec.AccountTypeCode = "WCS" AndAlso ec.AccountStatus = 5 AndAlso Not processedTermMembers.Any(Function(term) term.EmployeeID = ec.EmployeeID AndAlso term.FirstName = ec.EmployeeFirstName AndAlso term.LastName = ec.EmployeeLastName)).ToList()
    

    What the modified LINQ statement does is pull in the records from db.ECs where the AccountTypeCode is not "WCS", the AccountStatus is not 5, and is not in the processedTermMembers collection.