Taking an object from a list by reference and not by position

Asked

Viewed 599 times

2

Hello, I would like to know how to create a list of objects in C#, but instead of picking them by posição ([0], [i]), I want to take by reference [LacoAzul] [CorVermelha]. You can create a list like this?

Thanks in advance!

1 answer

4


There are some Framework classes that work like this.

You can use a dictionary. In a dictionary there is no order. You access the elements by keys. The key can be of any type - if it is a type by reference, then you can pass the reference of one object to get the other object of the pair key-value.

Maybe a hash table (with the class Hashtable) also solve your problem. Just like the dictionary it also works with pairs of key-value, but it’s a simpler structure. editing: the Hashtable class is now obsolete.

P.S.: whether the goal is only whether the item is in the list, the generic list itself (class List) has the method Contains, indicating whether or not an item is on the list from its reference.

  • 1

    It was the dictionary I needed, thank you!

  • The advice of the dictionary is' good (and meets the requirements of the OP), but I do not agree with the hashtable. A HashTable was launched with . NET 1.0, but was deprecated with the release of . NET 2.0 which introduced Generics. Basically, the Generica class Dictionary<TKey, TValue> has replaced the non-Generic HashTable. Its use is not more' recommended.

  • 1

    @dcastro is right, I will edit.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.