I have a collection of objects in vb.NET. Each object has two different IDs, lets call them ID1 and ID2.
I need to be able to quickly find a specific object in the collection based on one of these IDs. In some cases I have ID1 and in other cases I have ID2. I'm current开发者_高级运维ly using the Collection data structure with ID1 as the key, but that doesn't help me when I need to find an object using ID2.
Is there a better data structure to use?
Thanks
If you really need fast data access, you won't get around using two data structures, one mapping ID1 -> yourObject and another one mapping ID2 -> yourObject. I recommend the generic Dictionary(Of TKey, TValue) class instead of the (a bit outdated) Collection class, which is mainly a VB6 compatibility thing. If you go for the two-data-structure-approach, you will have to manually keep them synchronized. (You should probably create a separate class TwoKeyDictionary
for this where all the synchronization logic is centralized.)
On the other hand, if performance is not an issue, you could use an arbitrary data structure (even a list or a set) and use LINQ for easy access:
Dim lst As List<MyClass> = ...
Dim myObject = (From entry In lst Where entry.ID1 = ...).FirstOrDefault()
Of course, you could use a combined approach if fast access is only required for either ID1 or ID2. Then you can make one dictionary based on ID1 and use LINQ for searching this dictionary via ID2.
精彩评论