For me it seems to be obvious that a dictionary might have a method for getting it's item by Key
. Either I am blind, or...
However, I have following situation:
A need a Dictionary(Of Integer, k/v)
. I have the k/v
's already in a Dictionary
and I'd like to add them to my new one by Key
, such as:
'Dict1 has {("Key1", 123), ("Key2", 345)}
Dim dict2 As New Dictionary (Of Integer, KeyValuePair(Of String, Double))
dict2.Add(0,***dict1.GetItem("Key1")***)
Sure I could write an extension, and probably I'll have to, but is it only me missing this function? If there was a built in way I've overseen, please point me there!
Thanks in advance,
Daniel
EDIT:
dict1 = {(0, "apples"), (1, "oranges"), (2, "bananas")}
dict2 = {("oranges", 456), ("apples", 123), ("bananas", 789)}
the new dictionary is a sorted dict2
by dict1
:
dictnew = {("apples", 123), ("oranges", 456), ("bananas", 789)}
So my approach was:
dicttemp = {(0, ("apples", 123)), (1, ("oranges", 456)), (2, ("bananas", 789))}'. `dicttemp` is a `SortedDictionary`.
Next I get the values of dicttemp
and transform them into a Dictionary
.
You're looking for dictionary's indexer.
Dim a As Double = dict1("Key1")
In some comment, OP said:
I need the whole item as k/v and add the item of dict1 to dict2!!!
Since a dictionary implements IEnumerable(Of T)
where T
is KeyValuePair(Of TKey, TValue)
, you can use Single(...)
LINQ extension method to find out a key-value pair by key:
Dim pair As KeyValuePair(Of String, Double) = dict1.Single(Function(item) item.Key = "key")
Since dictionary's Add
method has an overload to give a key-value pair as argument, I believe that adding dict1
key-value pair to dict2
is just about calling Add
in the second dictionary providing the obtained key-value pair from first dictionary:
dict2.Add(pair);