How can iterate in Dictionary in vb.net? - vb.net

I create a dictionary
Dim ImageCollection As New Dictionary(Of ConvensionImages, Integer)
and I fill that
For Each dr As DataRow In dt.Rows
Dim obj As New ConvensionImages
obj.ImageID = dr("ID")
obj.Name = dr("Name")
obj.Description = dr("Description")
obj.CategoryID = dr("CategoryID")
obj.CategoryName = dr("CategoryName")
obj.CategoryDescription = dr("CatDescription")
obj.EventID = dr("EventID")
obj.Image = dr("img")
obj.DownloadImage = dr("DownLoadImg")
ImageCollection.Add(obj, key)
key = key + 1
now I want to search ImageID and key how can I do this

Make Integer as key for your Dictionary:
Dim ImageCollection As New Dictionary(Of Integer, ConvensionImages)
Change ImageCollection.Add(obj, key) to ImageCollection.Add(key, obj)
And use this loop:
For Each kvp As KeyValuePair(Of Integer, ConvensionImages) In ImageCollection
Dim v1 As Integer = kvp.Key
Dim v2 As ConvensionImages = kvp.Value
'Do whatever you want with v2:
'If v2.ImageID = .... Then
Next

You can loop this way, too:
For Each iKey As Integer In ImageCollection.Keys
Dim value As ConvensionImages = ImageCollection(iKey)
'...
Next
It is very fast and simple way to it.

Related

Retrieve values from a List

I want to store 100 items in a list with properties PartName and PartId.
I then want to search on PartName, as an example using the word chair. From this I then want to retrieve the value of PartId.
In the end I will end up with a PartId of 125.
How can I do this?
Code:
Dim parts As New List(Of Intialization)()
' Add parts to the list.
parts.Add(New Intialization() With {.PartName = "chair",
.PartId = 125})
You could achieve this in several ways, I´ll show you some LINQ solutions:
Dim partToSearch as String = "Chair"
Dim partId as Integer = -1
Dim init = parts.Where(Function(p) p.PartName=partToSearch).FirstOrDefault()
If init IsNot Nothing Then
partId = init.PartId
End If
Or:
Dim partToSearch as String = "Chair"
Dim partId = parts.Where(Function(p) p.PartName=partToSearch).Select(Function(v) v.PartId).FirstOrDefault()
Or you create a Dictionary like #the_lotus mentioned:
Dim partIDsByName as Dictionary(Of String, Integer)
partIDsByName = parts.ToDictionary(Function(k) k.PartName, Function(v) v.PartId)
Dim partToSearch as String = "Chair"
Dim partId = partIDsByName(partToSearch)

How to convert 2 dimensional arraylist to datatable?

I need a function that returns a datatable, from any arraylist (2 dimensions) as arguments? Thanks for your help
Creating two dimensional Arraylist:
Public Overrides Function Find(Optional ByRef conditions As ArrayList = Nothing) As System.Collections.ArrayList
Dim collection As New ArrayList
Dim cmd ......... ' Select command based on an arraylist of conditions
Dim dr As SqlDataReader = cmd.ExecuteReader()
While dr.Read()
Dim cnt As New contact
cnt .Id() = dr("id")
cnt .Name= dr("name")
'......... other columns are imported
collection.Add(cnt )
End While
dr.Close()
Return collection
End Function
Suitable solution found:
Public Shared Function ArrayListToDataTable(ByVal arraylist1 As ArrayList) As System.Data.DataTable
Dim dt As New System.Data.DataTable()
For i As Integer = 0 To arraylist1.Count - 1
Dim GenericObject As Object = arraylist1.Item(i)
Dim NbrProp As Integer = GenericObject.GetType().GetProperties().Count
For Each item As PropertyInfo In GenericObject.GetType().GetProperties()
Try
Dim column = New DataColumn()
Dim ColName As String = item.Name.ToString
column.ColumnName = ColName
dt.Columns.Add(column)
Catch
End Try
Next
Dim row As DataRow = dt.NewRow()
Dim j As Integer = 0
For Each item As PropertyInfo In GenericObject.GetType().GetProperties()
row(j) = item.GetValue(GenericObject, Nothing)
j += 1
Next
dt.Rows.Add(row)
Next
Return dt
End Function
After 2 years, Let me answer this=>
Function ConvertArrayListToDataTable(ByVal arraylist As ArrayList) As DataTable
Dim dt As DataTable = New DataTable()
If arraylist.Count <= 0 Then
Return dt
End If
Dim propertiesinfo As PropertyInfo() = arraylist(0).GetType().GetProperties()
For Each pf As PropertyInfo In propertiesinfo
Dim dc As DataColumn = New DataColumn(pf.Name)
dc.DataType = pf.PropertyType
dt.Columns.Add(dc)
Next
For Each ar As Object In arraylist
Dim dr As DataRow = dt.NewRow
Dim pf As PropertyInfo() = ar.GetType().GetProperties()
For Each prop As PropertyInfo In pf
dr(prop.Name) = prop.GetValue(ar, Nothing)
Next
dt.Rows.Add(dr)
Next
Return dt
End Function

How can pass collection list between aspx pages?

I tried to create list of object type and get through session the class type list from another page,but it is not working simply coming out of the code when assigment is done.
Public Sub GetvalueContains(ByVal txtFilterText As String, ByVal strColPropertyName As String, ByVal collectionName As String)
Dim FilteredAgentsList As New List(Of Object)
FilteredAgentsList = CType(HttpContext.Current.Session("FilteredAgentsList"), Object)
AgentList = Session("AgentList")
FilteredAgentsList = CType(HttpContext.Current.Session("AgentList"), Object)
Dim FilteredAgentsListdetails As New List(Of Object)
FilteredAgentsListdetails = HttpContext.Current.Session("FilteredAgentsListdetails")
Dim indx As Integer = 0
Dim indexx As Integer = collectionName.IndexOf("_")
indexx = indexx + 1
Dim str As String = collectionName.Substring(indexx, collectionName.Length - indexx)
Dim grdagents As GridView = HttpContext.Current.Session("grdAgents")
If FilteredAgentsListdetails.Count > 0 Then
FilteredAgentsList = FilteredAgentsListdetails
End If
Dim AgentListTemp As List(Of Object) = HttpContext.Current.Session("AgentListTemp")
AgentListTemp = FilteredAgentsList
'FilteredAgentsListdetails = New List(Of Agents)
strColPropertyName = GetPropertyNameAtIndex(AgentListTemp, Convert.ToInt32(hdncellindex.Value))
txtFilterText = txtFilterText.Replace("*", "")
Dim resultList As IEnumerable(Of Object)
resultList = AgentListTemp.Where(Function(x) x.[GetType]().GetProperty(strColPropertyName).GetValue(x, Nothing).ToString().StartsWith(txtFilterText))
'AgentListTemp = CType(resultList.ToList(), List(Of Agents))
'FilteredAgentsListdetails = AgentListTemp
grdagents.DataSource = Nothing
grdagents.DataBind()
grdagents.DataSource = resultList
grdagents.DataBind()
End Sub
how to get the session value in above code?or any other method to pass list from one page to other.

How to add List as value in Hashtable

In vb.net If I have HashTable,key is integer and the value is a list of integers, how to append integers to the value of a given key,
I have tried it but each time I found the integer last added only, (the list only has the last item added).
Here is my code , where dt is DataTable object
Dim dt = report.getEvaluationReportByObjectiveGroupId(29)
Dim data As New Hashtable()
Dim dataEntry As DictionaryEntry
Dim res As String
For Each row As DataRow In dt.Rows
Dim strYear = row.Item("Year")
Dim strData = row.Item("EmpCount")
If data.ContainsKey(strYear) Then
Dim newCountArr As List(Of Int32) = DirectCast(data(strYear), List(Of Int32))
' newCountArr.AddRange(data(strYear))
newCountArr.Add(strData)
' data.Remove(strYear)
' data.Add(strYear, newCountArr)
Else
Dim countArr As New List(Of Integer)
countArr.Add(strData)
data.Add(strYear, countArr)
End If
' data.Add(strYear, strData)
Next row
I would suggest to use the strongly typed Dictionary(Of Int32, List(Of Int32)) instead, it works similar. But anyway, here's the HashTable approach:
Dim table = New Hashtable
Dim list = New List(Of Int32)
For i = 1 To 999
list.Add(i)
Next
table.Add(1, list)
' somewhere else you want to read the list for a given key (here 1) '
Dim list1 As List(Of Int32) = DirectCast(table(1), List(Of Int32))
list.Add(1000) ' add another integer to the end of the list '
' note: you don't need to add the list to the HashTable again '
Edit: Since you've posted your code, here's the corrected:
For Each row As DataRow In dt.Rows
Dim strYear = row.Field(Of Int32)("Year")
Dim strData = row.Field(Of Int32)("EmpCount")
Dim list As List(Of Int32)
If data.ContainsKey(strYear) Then
list = DirectCast(data(strYear), List(Of Int32))
Else
list = New List(Of Int32)
data.Add(strYear, list)
End If
list.Add(strData)
Next row

Building a multidimensional array in vb.net

I'm trying to build up a multidimensional array which will hold two bits of info for each record in a database e.g. id, description.
This is what I am currently doing.
Dim mArray(,) As String
Dim i As Integer = 0
While cmdReader.Read()
mArray(i,0) = cmdReader.Item("id")
mArray(i,1) = cmdReader.Item("description")
i = i + 1
End While
The problem I have here is that it doesn't like the i in mArray(i,0). Anyone have any ideas about this? This is the error that is given Object reference not set to an instance of an object.
Thanks for any and all help.
Nalum
Why not rather make use of List Class and Dictionary Class
You can rather then create a List of Dictionaries, with the key and value both strings. The key can then represent your key (id and description in your example, and the value can be what ever was stored).
Something like
Dim values As New List(Of Dictionary(Of String, String))()
and then in the while loop something like
values.Add(New Dictionary(Of String, String)() From { _
{"id", cmdReader.Item("id")} _
})
values.Add(New Dictionary(Of String, String)() From { _
{"description", cmdReader.Item("description")} _
})
You could then use foreach
For Each value As Dictionary(Of String, String) In values
Dim id As String = value("id")
Dim description As String = value("description")
Next
Or a for
For i As Integer = 0 To values.Count - 1
Dim value As Dictionary(Of String, String) = values(i)
Dim id As String = value("id")
Dim description As String = value("description")
Next
Try this
Dim mArray(1,1) As String
Dim i As Integer = 0
While cmdReader.Read()
mArray(i,0) = cmdReader.Item("id")
mArray(i,1) = cmdReader.Item("description")
i = i + 1
ReDim Preserve mArray(i,1)
End While
The problem is that you are not initializing the array.
This should work, until i will not reach the limits set in the initialization.
Dim mArray(100,100) As String
Dim i As Integer = 0
While cmdReader.Read()
mArray(i,0) = cmdReader.Item("id")
mArray(i,1) = cmdReader.Item("description")
i = i + 1
End While
But if the array limits are not known I suggest to follow astander's suggestion.
This works for me:
Dim values As New List(Of Dictionary(Of String, String))()
values.Add(New Dictionary(Of String, String)() From {{"quarter", q1.ToString}, {"year", y1.ToString}})
values.Add(New Dictionary(Of String, String)() From {{"quarter", q2.ToString}, {"year", y2.ToString}})
values.Add(New Dictionary(Of String, String)() From {{"quarter", q3.ToString}, {"year", y3.ToString}})
values.Add(New Dictionary(Of String, String)() From {{"quarter", q4.ToString}, {"year", y4.ToString}})
For Each value As Dictionary(Of String, String) In values
Dim quarter As String = value("quarter")
Dim year As String = value("year")
Debug.Print(quarter & "/" & year)
Next
Correct it by
Dim mArray(,) As String = ""