[Okta Webinar] Learn how to a build a cloud-first strategyRegister Now

  • Status: Solved
  • Priority: Medium
  • Security: Public
  • Views: 3639
  • Last Modified:

VB.Net Generic List Get Unique Values By A Single Property

I have a Generic LIst I need to populate another Generic List with Only the Unique Objects bases Only on a single Property called Name.

I'm using .Net 2.0 - I can't use LINQ !   (Which would be easy...)

Any ideas of the best way... thanks

  • 3
2 Solutions
I think you need distinct "Name" from Objects in MyList.
For that, use a dictionary:

Dim D as new Dictionary (of String,MyObjectType)(MyList.Count)
For each e in MyList
   if D.Contains(e.Name) = False then D.Add(Name, e)
Dim NewList as List(of String)(D.Keys) '        Dim NewList as List(of MyObjectType)(D.Values)
actually there is an easier way with the list but I don't know the VB syntax. I ll fire up VS2008 and let you know in a minute.
ok I finally found out the syntax (I hate VB...):

The idea is to use Linq's Distinct() method and provide it with a method to compare your objects (see code below).

Another solution could be to do a group and then select one element (the first or last or whatever):
Dim distinctList = fullList.GroupBy(Function(n) n.Name).Select(Function(o) o.First())

Public Class NameCompare
        Implements System.Collections.Generic.IEqualityComparer(Of MyObject)

        Public Function Equals1(ByVal x As MyObject, ByVal y As MyObject) As Boolean Implements   System.Collections.Generic.IEqualityComparer(Of MyObject).Equals
            Return IIf(x.Name = y.Name, True, False)
        End Function

        Public Function GetHashCode1(ByVal x As MyObject) As Integer Implements System.Collections.Generic.IEqualityComparer(Of MyObject).GetHashCode
            Return x.Name.ToString.ToLower.GetHashCode()
        End Function
    End Class

Dim fullList As List(Of MyObject)
Dim distinctList = fullList.Distinct(New NameCompare())

Open in new window

mmmmm never mind that ... I just realised in your question that you can't use Linq (I read the contrary).

Featured Post

Concerto's Cloud Advisory Services

Want to avoid the missteps to gaining all the benefits of the cloud? Learn more about the different assessment options from our Cloud Advisory team.

  • 3
Tackle projects and never again get stuck behind a technical roadblock.
Join Now