[RESOLVED] Composite key with class collection
I want to be able to get an instance of a class based on two fields in that class. I was hoping to use something like a dictionary, because I thought indexing would be the best for performance. Should I just use LINQ or go back to a strongly typed dataset? Here's an example of what I'm trying to do:
Code:
Dim n As New Name("wild", "bill")
Dim dict As New Dictionary(Of String(), Name)
dict.Add(New String() {"wild", "bill"}, n)
Dim key() = New String() {"wild", "bill"}
Debug.WriteLine(dict.ContainsKey(key)) 'false
...
Public Class Name
Public FirstName As String
Public LastName As String
Public NameCount As Integer
Public Sub New(ByVal first As String, ByVal last As String)
Me.FirstName = first
Me.LastName = last
End Sub
End Class
Re: Composite key with class collection
Using a Dictionary would probably perform better but that would only really be a benefit if you are accessing the collection a lot or it is very large. If you are going to use a Dictionary then I would suggest against using a String array as the key. I would suggest defining a type specifically for the purpose with two String properties and its own GetHashCode function override based on those two properties.
A simpler option would be to just use a List and a LINQ query, e.g.
vb.net Code:
Dim name = names.FirstOrDefault(Function(n) n.FirstName = firstName AndAlso n.LastName = lastName)
Re: Composite key with class collection
Thanks for the input, I went ahead and used LINQ. My collection will typically never be over 1,000 items.