How can i change the values in a dictionary that are inside another dictionary? - vb.net

I've come here after hours of looking on the internet. Nothing comes close to what I am trying to achieve.
I have this:-
Private Portfolio_Client_List As New Dictionary(Of String, Dictionary(Of String, Double))
which I then add keys to like the following:-
Portfolio_Client_List.Add(str.Substring(6, 5).Trim, New Dictionary(Of String, Double))
then I add keys to the other dictionary like the below:-
For Each pair As KeyValuePair(Of String, Dictionary(Of String, Double)) In Portfolio_Client_List
pair.Value.Add("Office Collections", 0.00)
pair.Value.Add("Home Collections", 0.00)
Next
Now I want to update the values in the Office Collections and Home Collections keys values.
How can I do so? I thought it would be as simple as:-
For Each pair As KeyValuePair(Of String, Double) In Portfolio_Client_List("key")
pair.Value += Head_Office_Payments
Next
However it just gives me the readonly error. Is there any way to do this, or am I wasting my time?

No, KeyValuePairs are immutable structs, so you can't modify them, Value is readonly.
But this works (you want to add Head_Office_Payments to the old value):
Dim dict As Dictionary(Of String, Double) = Portfolio_Client_List("key")
For Each key As String In dict.Keys.ToList()
dict(key) += Head_Office_Payments
Next
Note that you need the dict.Keys.ToList(creates a new list) because you can't modify the collection while enumerating, setting the Value of a dictionary increases it's version number which invalidates the iterator. That's why i prefer this one-liner LINQ solution:
dict = dict.ToDictionary(Function(kv) kv.Key, Function(kv) kv.Value + Head_Office_Payments)

Related

Which overload of todictionary that I use if I do this?

Dim dict1 = fileToDict(PriceList)
Dim dict2 = dict1.ToDictionary(Function(y) Val(y))
Basically I am turning dict(of string,string) to dict(of string, double).
My question is I do not see any overload of toDictionary that takes a single function of stuff.
Note: The correct format is actually
Dim dict2 = dict1.ToDictionary(Function(x) x.Key, Function(y) Val(y.Value))
All of the overloaded operator takes 1 function that takes a keyvaluepair as argument.
Somehow the one that works use 2 function. That's where I am confused.
You need to specify a selector for both the keys and the values. There's no overload that is going to simply take the keys from the original Dictionary. Remember that ToDictionary is actually called on an IEnumerable(Of T) so it has no idea that the source is a Dictionary. It only knows that it is an IEnumerable(Of KeyValuePair(Of String, String)). You have to tell it how to get the keys for the new Dictionary from the items in the IEnumerable(Of T) source.
E.g.
Dim dict2 = dict1.ToDictionary(Function(kvp) kvp.Key, Function(kvp) CDbl(kvp.Value))

How to use reflection to get keys from Microsoft.VisualBasic.Collection

I know that it is not possible to get keys (How to get the Key and Value from a Collection VB.Net) and it is better to use other classes. However I am debugging 10 years old code and I cannot change it.
In the Watch Window I see:
So it seems to be possible to deal the collection as "List(of KeyValuePair)". Can I do it in code or is it only an internal translation.
I basically need to list all KEYs in a Collection.
VisualBasic.Collection has an undocumented private method InternalItemsList which allows reading keys besides values. The type of InternalItemsList is Microsoft.VisualBasic.Collection.FastList which does not seem to be Enumerable but has a method Item which returns items with a zero based index. The type of those items is Microsoft.VisualBasic.Collection.Node. An item has two private properties m_Value and m_Key. And here we are.
Following code illustrates how to convert VisualBasic.Collection to List(Of KeyValuePair.
Dim flg As BindingFlags = BindingFlags.Instance Or BindingFlags.NonPublic
Dim InternalList As Object = col.GetType.GetMethod("InternalItemsList", flg).Invoke(col, Nothing)
Dim res As New List(Of KeyValuePair(Of String, Object))
For qq As Integer = 0 To col.Count - 1
Dim Item As Object = InternalList.GetType.GetProperty("Item", flg).GetValue(InternalList, {qq})
Dim Key As String = Item.GetType.GetField("m_Key", flg).GetValue(Item)
Dim Value As Object = Item.GetType.GetField("m_Value", flg).GetValue(Item)
res.Add(New KeyValuePair(Of String, Object)(Key, Value))
Next
I know that using undocumented functions is not safe but it is for internal use only and only solution I have managed to find.

List of Dictionary Arrays

Hit a wall, and can't find much in docs.
I have two dictionaries, and I'd like to put them in a list.
Dim listOfDictionaries As List(Of Dictionary(Of String, String))
is not working.
Am I correct in assuming that once I get this dimmed, I can .add the conventional way?
Details (EDIT)
When trying to listOfDictionaries.Add(dictionaryIWantToAdd), I get "value of type '1-dimensional array system.collection.generic.dictionary(of string, string)' cannot be converted to 'system.collection.generic.dictionary(of string, string)'
Solution
Helps to put the () on the end an array. :P
The conventional way is:
Dim both = New List(Of Dictionary(Of String, String))()
both.Add(Dictionary1)
both.Add(Dictionary2)
The error says it all. You are trying to add an array of dictionaries to the list, but the add method only takes a single dictionary, not an array of them. Either fix it so you are only passing in a single dictionary:
Dim myDictionary As Dictionary(Of String, String)
' ...
listOfDictionaries.Add(myDictionary)
Or use the AddRange method to add all the dictionaries in the array at once:
Dim myArrayOfDictionaries() As Dictionary(Of String, String)
' ...
listOfDictionaries.AddRange(myArrayOfDictionaries)
I tend to favour single-line solutions when it's something straightforward like this, making use of the From keyword.
Dim listOfDictionaries = New List(Of Dictionary(Of String, String)) From { dictionary1, dictionary2 }

VB.Net Order a Dictionary(Of String, Integer) by value of the Integer

I have a dictionary of String, Integer so the key is the string and the value is the integer and i want to order the keys ascending by the value of the integer. How could I achieve this?
You could use LINQ to sort the Dictionary by value:
Dim dictionary = New Dictionary(Of String, Integer)()
dictionary.Add("A", 2)
dictionary.Add("B", 4)
dictionary.Add("C", 5)
dictionary.Add("D", 3)
dictionary.Add("E", 1)
Dim sorted = From pair In dictionary
Order By pair.Value
Dim sortedDictionary = sorted.ToDictionary(Function(p) p.Key, Function(p) p.Value)
Actually it does not modify the original Dictionary but creates a new Dictionary with the new order.
But: Apart from the feasability, a Dictionary is not an IList (as an Array or List<T>). It's purpose is to lookup a key very efficiently but not to loop all entries.
They are unordered, meaning that although you can retrieve the elements in some order with a foreach loop, that order has no special meaning, and it might change for no apparent reason.
First of all, a dictionary does not have an intrinsic order. It is for look-ups. However, you can turn the keys into their own ordered list.
Dim keyList as List(Of String) = (From tPair As KeyValuePair(Of String, Integer) _
In myDictionary Order By tPair.Value Ascending _
Select tPair.Key).ToList
I had to do something similar to this with custom objects. I think this should be close (but may not be exactly) what you're looking for:
Dim sortedL As List(Of KeyValuePair(Of String, Integer)) = yourDictionary.ToList
sortedL.Sort(Function(firstPair As KeyValuePair(Of String, Integer), nextPair As KeyValuePair(Of String, Integer)) CInt(firstPair.Value).CompareTo(CInt(nextPair.Value)))

nested dictionaries

I've got a nested dict like:
Public collectionMain As New Dictionary(Of String, Dictionary(Of String, String))
When inserting a new item:
collectionMain.Add(node.SelectSingleNode("key").InnerText.Trim, collectionSub)
collectionSub.Clear()
On the add my collectionSub is filled with key & values.
But when calling clear, the collectionMain.value is empty.
How can i keep the collectionMain dictionary value?
The collectionSub needs to be cleared, it's in a loop for filling.
thank you
You need to create a New Dictionary(Of String, String) for each value.
Whenever you add a new dictionary item, you will have to declare a new sub-dictionary for that key:
collectionMain.Add(node.SelectSingleNode("key").InnerText.Trim, _
New Dictionary(Of String, String))
The collectionSub variable really should not exist since every key in collectionMain has it's own dictionary.
Do not clear collectionSub. Don't forget that you are adding reference of Dictionary(Of String, String) - collectionSub. If you want to clear that object then you must have to create a "clone" (deep copy) of collectionSub. Take a look at SO thread - What is the best way to clone/deep copy a .NET generic Dictionary?