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
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.
You can use List<KeyValuePair<string,int>> . This will store a list of KeyValuePair 's that can be duplicate.
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.
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.
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>>
.
you can use
List<KeyValuePair<string,object>>
or
Dictionary<string,List<object>>
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With