Unique array of vb.net structures

I have a structure

Public Structure MyRecords
    Dim record_name As String
    Dim record_surname As String
End Structure

      

and an array of structures

Dim Records_arr(100000) AS MyRecords

      

The array is filled with data, but I want to remove the duplicate MyRecords

.

Duplicate means:

Records_arr(3).record_name = "John"
Records_arr(3).record_surname = "Doe"

Records_arr(99).record_name = "John"
Records_arr(99).record_surname = "Doe"

      

In this example, I want to delete Records_arr(3)

or Records_arr(99)

or just delete the values ​​of one of them.

I have already implemented a two-pass top-down and then bottom-up scan that wipes out duplicates, but very slowly. There must be a better way?

+3


source to share


1 answer


Inject IEquatable<T>

into your structure and then use the LINQ function Distinct()

to get your goals.

Here's an example implementation:

Public Structure MyRecords
    Implements IEquatable(Of MyRecords)

    Dim record_name As String
    Dim record_surname As String

    Public Function Equals1(other As MyRecords) As Boolean Implements IEquatable(Of MyRecords).Equals
        Return record_name.Equals(other.record_name) AndAlso record_surname.Equals(other.record_surname)
    End Function
End Structure

      

Now you can call Records_arr.Distinct()

and it will return unique entries of your array.

Further explanation



In response to your comment, here's what's going on. Since you're using Structure

, not Class

, MyRecords

already inherits the method ValueType.Equals()

. For value types that do not contain reference type members, the method Equals()

performs a byte comparison of two objects in memory. On the other hand, if it contains elements of a reference type (this is your case), it uses Reflection to compare the corresponding fields of the two instances. You have two fields String

in your structure that are reference types and are therefore compared via Reflection. (It's important to note that the class String

, although a reference type, overrides Equals()

to provide value comparison instead of standard reference comparison). This way, even if you don't implement IEquatable

or IComparable

in your class,Distinct()

will work fine using the default function ValueType.Equals()

.

Note, however, that MSDN asks you to provide an implementation Equals()

for such structures. Here's a relevant passage:

In particular, if your value type contains fields that are reference types, you must override the Equals (Object) method. This can improve performance and give you a more accurate idea of ​​the value of equality for a type.

Read more about this in this MSDN article .

+4


source







All Articles