associative array like in php in vb.net - vb.net

in PHP we know to make associative array using this code
$variable = array('0001'=>'value1', '0010'=>'value2');
and to print all keys and values using this code
foreach($variable as $key1 => $val1)
foreach($val1 as $key2 => $val2)
echo ("$key2 => $val2 <br />")
and the question is how to perform this in vb.net?
as i know to make associative array in vb.net using this :
Dim var As New Collection
var.Add("value1", "0001")
var.Add("value2", "0010")
how about to print value and key in vb.net like foreach in PHP? thanks

Although i'm not familiar with PHP (anymore), i assume that associative arrays are the equivalent of a HashTable or the more modern, strongly typed Dictionary:
Dim dict = New Dictionary(Of String, String)
dict.Add("value1", "0001")
dict.Add("value2", "0010")
Normally you would lookup keys:
Dim val2 = dict("value2") ' <-- 0010
But if you want to enumerate it (less efficient):
For Each kv As KeyValuePair(Of String, String) In dict
Console.WriteLine("Key:{0} Value:{1}",kv.Key, kv.Value)
Next

Dim row As Dictionary(Of String, Object)
Dim rows As Dictionary(Of String, Object)
row = New Dictionary(Of String, Object)
rows = New Dictionary(Of String, Object)
row.Add("a", 11)
row.Add("b", 22)
rows.Add("ab", row)

Related

how to convert value in a keypairs into list?

Dim dict As New Dictionary(Of String, KeyValuePair(Of String, String))
dict.Add("key", New KeyValuePair(Of String, String)("value1","value2"))
I want to get value2 as a list.
Using LINQ Extensions:
' use KeyValuePair of dictionary, that gives 2 levels of KeyValuePairs
Dim list = dict.Select(function(kvp) kvp.Value.Value).ToList()
' Or use the Values part of Dictionary
Dim list = dict.Values.Select(function(v) v.Value).ToList()
' Adding some conditional and getting value1 instead:
Dim list = dict.Values.Where(function(k) k.Value = "value2").Select(function(v) v.Key).ToList()
For KeyValuePair x.Key is "value1" and x.Value is "value2"
Please note that this will get quite slow on big Dictionarys and there is probably better ways to handle this, but that requires more information about The actual use-case.

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)))

Compare two lists 2D and determine differences VB.NET

I declare my 2D lists:
Dim _invoiceitems As New List(Of List(Of String))
Dim _dbitems As New List(Of List(Of String))
Each List is filled like this:
Example Code To fill:
_invoiceitems.Add(New List(Of String))
_invoiceitems(0).Add("Code #")
_invoiceitems(0).Add("Quantity")
Well, now i need a third list called (_changesitems) Note that this result with the differences:
be the result of subtraction of quantities if this is found (dbitems - invoiceitems).
How i can get this result?
The following code will generate the results you are looking for:
Private Function getChangesItems(ByVal invoiceItems As Dictionary(Of String, Integer), ByVal dbItems As Dictionary(Of String, Integer)) As Dictionary(Of String, Integer)
Dim changesItems As Dictionary(Of String, Integer) = New Dictionary(Of String, Integer)()
Dim allCodes As List(Of String) = New List(Of String)()
allCodes.AddRange(invoiceItems.Keys)
allCodes.AddRange(dbItems.Keys)
For Each code As String In allCodes
If Not changesItems.ContainsKey(code) Then
Dim dbQuantity As Integer = 0
Dim invoiceQuantity As Integer = 0
If dbItems.ContainsKey(code) Then
dbQuantity = dbItems(code)
End If
If invoiceItems.ContainsKey(code) Then
invoiceQuantity = invoiceItems(code)
End If
Dim changeQuantity As Integer = dbQuantity - invoiceQuantity
If changeQuantity <> 0 Then
changesItems.Add(code, changeQuantity)
End If
End If
Next
Return changesItems
End Function
I used dictionaries instead of lists as was recommended by others. As long as your data only contains a code and a value, the dictionary is a better fit. If you have more columns, I would suggest creating a class that contains properties for each column and then make a list of that class type, rather than a simple 2D list of strings. Doing so would be more type-safe and easier to read.

Compile error while adding items to nested dictionary

I am trying to created nested dictionary variable like the below, But I get compile error stating that it needs "}" at line where I am adding items (line #2) to my nested dictionary.
What Am I missing here? Thanks.
Dim myNestedDictionary As Dictionary(Of String, Dictionary(Of String, Integer)) = New Dictionary(Of String, Dictionary(Of String, Integer))()
myNestedDictionary.Add("A", New Dictionary("A", 4)())
In VS 2008 and .net 3.5 you cannot declare and initialize a Dictionary in one line, so you have to do:
Dim myNestedDictionary As New Dictionary(Of String, Dictionary(Of String, Integer))()
Dim lTempDict As New Dictionary(Of String, Integer)
lTempDict.Add("A", 4)
myNestedDictionary.Add("A", lTempDict)
To retrieve the an item use the following:
Dim lDictionaryForA As Dictionary(Of String, Integer) = myNestedDictionary.Item("A")
Dim lValueForA As Integer = lDictionaryForA.Item("A")
The value in lValueForA should be 4.
You need to specify the type of dictionary you are creating when you add the records:
myNestedDictionary.Add("A", New Dictionary(Of String, Integer))
or otherwise pass an existing Dictionary(Of String, Integer) as the inside-dictionary argument (when adding key/value pairs to the external dictionary).
(BTW, Your external dictionary is a dictionary who's Keys are Strings and Values are Dictionaries (Of String, Integer), is this really what you wanted?)
In C# you can do that:
var myNestedDictionary = new Dictionary<string, Dictionary<string, int>>() {{ "A", new Dictionary<string, int>() { { "A", 4 } } }};
You can do it in VB 2010 as well, using the From keyword, but it doesn't compile in VS 2008. It will compile in VB 2010, no matter which .NET Framework you target. I've tried 2.0, 3.5 and 4.0.
Dim myNestedDictionary = New Dictionary(Of String, Dictionary(Of String, Integer))() From {{"A", New Dictionary(Of String, Integer) From {{"A", 4}}}}