Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is there Dictionary<Key,Value> without unique key? [duplicate]

Tags:

c#

.net

Possible Duplicate:
Duplicate keys in .NET dictionaries?

I need to create a Collection<string,object>, one is a string and another one is an object. I cannot use Dictionary since none of items is unique.

Is there any way to create List<T,T> ? Since i don't want to create an object to hold both values just to use it in single foreach loop.

Thanks

like image 331
eugeneK Avatar asked Jul 10 '12 08:07

eugeneK


People also ask

Can a dictionary have duplicate keys?

Why you can not have duplicate keys in a dictionary? You can not have duplicate keys in Python, but you can have multiple values associated with a key in Python. If you want to keep duplicate keys in a dictionary, you have two or more different values that you want to associate with same key in dictionary.

Can key value pair have duplicate keys?

You can use List<KeyValuePair<string,int>> . This will store a list of KeyValuePair 's that can be duplicate.

Does dictionary key have to be unique?

No, each key in a dictionary should be unique. You can't have two keys with the same value. Attempting to use the same key again will just overwrite the previous value stored. If a key needs to store multiple values, then the value associated with the key should be a list or another dictionary.

What happens when you try to add a duplicate key in a dictionary?

As other have said, it is not possible to add duplicate key in dictionary. How about using Dictionary<string, List<string>>? Then check if the key exist then add the line in the list value for that key and if the key does not exist then create a new entry in the dictionary.


2 Answers

Try List<Tuple<string, object>>. Then you can get the usual linq support over the list to get at each Tuple<string, object>.

The Tuple<,> class is available as of .NET 4 onwards, but you can easily mimick a tuple type of your own without too much hassle.

I think that tuples are considered equal based on their item values, but with object this would likely be reference equals and thus shouldn't likely be equal... if that made any sense!

More info on equality here:

Surprising Tuple (in)equality

Update:

If you need to associate a list of items with a key for the purposes of a lookup, the duplicate question answer correctly highlights the Lookup class (in your case, Lookup<string, object>), which would express your intent a little clearer than a List<Tuple<string, object>>.

like image 139
Adam Houldsworth Avatar answered Sep 20 '22 17:09

Adam Houldsworth


you can use

List<KeyValuePair<string,object>> 

or

Dictionary<string,List<object>> 
like image 23
Rzv.im Avatar answered Sep 19 '22 17:09

Rzv.im