Question

My issue is the following:

Dim dt As DataTable = GetSomeDataTable()
Dim exceptions As List(Of String())({{"a","b"},{"c","d"}})
For Each j As Integer In Enumerable.Range(0, dt.Rows.Count) _
                                   .Where(Function(j1) exceptions.Contains({CStr(dt.Rows(j1)(0)), CStr(dt.Rows(j1)(1)}))
    ' Do something
Next

In the above, the code in the loop never executes even if there are rows in dt with first element "a", second element "b" for example, because the IEnumerable.Contains method doesn't match one array {"a", "b"} with another array {"a", "b"}. I'm guessing the comparison is done by reference rather than by value? What I want is for the Contains method to consider two arrays A and B equal iff A(i) = B(i) for all i = 0, 1, ... . I've noticed this behavior with the IEnumerable.Distinct() as well and managed to overcome it by making a custom EqualityComparer, but I felt this was quite cumbersome. Does anyone know a slicker way to achieve this? Or just a general way to compare multiple-element primary keys in .Net? (Concatenating the strings with an illegal character doesn't count.)

Was it helpful?

Solution

Your problem is that you try to compare arrays. You're right that the comparison is done by reference rather than by value. Either use another type like Tuple, or use Join (which is also probably faster than the Where/Contains combo):

Dim rows = from row in dt.AsEnumerable()                     
           join e in exceptions on row(0) Equals e(0) And row(1) Equals e(1)

For Each row in rows
    ' do something '
Next
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top