How to get a collection of elements in my dictionary that meet a given condition? - vb.net

I am going through some pluralsight videos and I found this amazing one called "Beautiful C++ 14: STL Alorithms". In this video the instructor discusses using the a variation of find_if methods like the one below.
vector<int> v{ 4, 6, 6, 1, 3, -2, 0, 11, 2, 3, 2, 4, 4, 2, 4 };
//find the first zero in the collection
auto result = find(begin(v), end(v), 0);
These methods are fantastic and I will be using it for some of my C projects, but I am currently working in a VB project where I need some kind of the same functionality.
I have a dictionary and I need to get certain objects out of it based on an if statement.
Structure Example_Struct
Public ExampleItem1 As Integer
Public ExampleItem2 As Integer
End Structure
Private Example_Dictionary As New Generic.Dictionary(Of String, Example_Struct)
Private Sub PopulateDictionaryWithDummyData()
Dim dummyData1 As Example_Struct
Dim dummyData2 As Example_Struct
dummyData1.ExampleItem1 = 1
dummyData1.ExampleItem2 = 1
dummyData1.ExampleItem1 = 5
dummyData1.ExampleItem2 = 5
Example_Dictionary.Add("Data1", dummyData1)
Example_Dictionary.Add("Data2", dummyData2)
End Sub
Private Sub LoadData()
PopulateDictionaryWithDummyData()
Dim stIdx As Integer
Dim myStruct As New Example_Struct
Dim item1 As Integer = 5
Dim item2 As Integer = 5
Dim count As Integer = Example_Dictionary.Count
For stIdx = 1 To count
' Get the stand data
myStruct = Example_Dictionary.ElementAt(stIdx).Value
If (myStruct.ExampleItem1 = item1 And myStruct.ExampleItem1 = item2) Then
' Do Something
End If
Next
End Sub
Above is some sample code to test with were I populate my Example_Dictionary with some dummy data. Then loop through the dictionary and put the comment where I need to do some things.
I would like my code to take the for loop out of the picture completley, just grab the "Example_Struct" that matches my conditions.
If there are more than one "Example_Struct" that matches my condition, I would need it to return a collection of these.

To filter the dictionary values based on a certain condition, you may use something like the following:
Dim myStructs = Example_Dictionary.Values.
Where(Function(x) x.ExampleItem1 = item1 AndAlso x.ExampleItem2 = item2).ToList()
Note that when dealing with logical operations, it's always a good idea to use the short-circuit logical operators (i.e., AndAlso instead of And and OrElse instead of Or). You can learn more about the difference in this guide:
Logical and Bitwise Operators in Visual Basic

Related

Associating a list with another that has been sorted

I have two lists, one integer and one string. These values are entered during a loop, so they are associated together (e.g. ListOfInteger.Item(i) and ListOfString.Item(i) were entered at the same time and are related to each other). I sorted and subsequently reversed the list of integers. Is there any way to have the list of strings still associated with the list of integers, in order to display them in a text box. For example:
List of Strings (surname): List of Integers (score):
Jones 4
Perry 2
Morris 6
List of Strings (surname): Sorted List of Integers:
Jones 2
Perry 4
Morris 6
Edit:
If (name.Count + 1) < compnum Then
name.Add(txtName.Text)
score.Add(txtScore.Text)
Else
txtName.Text(Hide)
txtScore.Text(Hide)
btnSort.Text(Show)
End If
...
score.Sort()
score.Reverse()
txtSortedScore1.Text = score(0)
(and so forth)
How can I relate these two lists together in order to associate the data in the string list with the sorted list of integers?
Edit - The end result should look like this:
List of Strings (surname): Sorted List of Integers:
Perry 2
Jones 4
Morris 6
The techniques suggested by the others to use a container class or dictionary are better solutions. However to answer the question as stated, what you seeking to do is perform a keyed sort. Unfortunately, the List(Of T) class does not provide this functionality; it is provided by the Array Class.
This is a bit convoluted as first you dump the two lists to arrays, sort the arrays, and finally recreate the lists with the sorted results.
Dim keysList As List(Of Int32) = New List(Of Integer)(New Int32() {4, 2, 6})
Dim itemsList As List(Of String) = New List(Of String)(New String() {"Jones", "Perry", "Morris"})
Dim keys As Int32() = keysList.ToArray
Dim items As String() = itemsList.ToArray
Array.Sort(keys:=keys, items:=items)
keysList = New List(Of Integer)(keys)
itemsList = New List(Of String)(items)
You should wrap your string and integer in another object.
Class Person
Public String SurName
Public Int Score
End Class
From there you can manipulate your objects in any way you like and then iterate over them and output the data as you like.
Something like this:
Dim persons = New List(Of Person)()
persons.Add(New Person() With { _
Key .SurName = "Jones", _
Key .Score = 4 _
})
For Each p As var In persons.OrderBy(Function(x) x.Score)
ListBox.Add(p.SurName + p.Score)
Next
If you would provide your code, we could help you more.
There are few ways the names can be sorted. Here is one way:
Dim names = {"Jones", "Perry", "Morris"}, score = {4, 2, 6}
Dim sortedIndexes = Enumerable.Range(0, score.Length).OrderBy(Function(i) score(i)).ToArray ' { 1, 0, 2 }
Dim sortedNames = sortedIndexes.Select(Function(i) names(i)).ToList ' { "Perry", "Jones", "Morris" }
Dim sortedScore = sortedIndexes.Select(Function(i) score(i)).ToList ' { 2, 4, 6 }

Fastest way to detect duplicate numbers on array vb.net 2005

I have this project that let user inputs 5 different numbers from 1 to 50. But I want to validate it before saving to DB that i will be 5 unique numbers. What's the best and fastest way to do this?
You can use HashSet(Of T) to check this:
Dim numbers As IEnumerable(Of Integer) = GetInputFromUser()
Dim hash As HashSet(Of Integer) = new HashSet(Of Integer)(numbers)
Dim unique As Boolean = hash.Count = numbers.Count()
This will be much more efficient than options requiring a sort + iteration.
Check this code
Private Function HasDuplicates(ByVal arr As Array) As Boolean
For i As Integer = 0 To arr.Length - 1
If Not arr(i) Is Nothing Then
Dim l As Integer = Array.LastIndexOf(arr, arr(i))
If l <> i Then Return True
End If
Next
Return False
End Function
Reed Copsey's suggestion to use hash sets was a good one (I hadn't worked with the HashSet class before).
But I then discovered that the IEnumerable class offers an extension method called Distinct that copies the unique values from a source IEnumerable to a target IEnumerable.
Borrowing the first line of Reed's sample code, here's the new sample VB.NET code:
Dim numbers As IEnumerable(Of Integer) = GetInputFromUser()
Dim isUnique As Boolean = (numbers.Distinct.Count = numbers.Count)
The variable isUnique is True if the numbers IEnumerable contains no duplicate values, or False if it contains one or more duplicate values.
Put in an array, sort it and check if elements 1,2 2,3 3,4 and 4,5 are different (in a loop).
Pseudocode:
integer numbers[50]
zeroarray(numbers, 50)
integer count = 0;
while (count < 5)
{
integer value = getinput()
if (value >= 1 and value <= 50)
if (numbers[value] = 0)
{
count = count + 1
numbers[value] = 1
}
else
reject duplicate
else
reject invalid
}
You can try this very simple method:
Filtering Arrays using LINQ
To simplifiy lets say the user inputs 5 different numbers from 0 to 49.
You can create a Boolean Array IsUsed(49) with 50 elements.
Then when the user input the value iInputNum=30 you can set IsUsed(30)=TRUE.
Next time, when the user input the second value iInputNum=7, you can set IsUsed(7)=TRUE
In this way you can check in a very fast way if the number was already inserted.
if IsUsed(iInputNum) then
'Skip the Input (put the right code here)
else
'Accept the number
IsUsed(iInputNum)=TRUE
'save iInputNum in the database
end if
Do not forget to clear the array after inserting all 5 numbers.
Remenber to put the right index in order to handle the number 1-50 (e not 0-49)
Here's an alternate solution, not sure how it compares, efficiency wise, to the other solutions, but it seems to work (uses LINQ).
Dim numbers As List<int> = getListOfNumbers()
Dim allUnique As Boolean = numbers.Distinct().Count() = numbers.Count()
Very late to the party, but what about something like this (C#, sorry)?
byte[] hits = new byte[51];
byte[] entries = new byte[] { 1, 12, 12, 32, 26, 49 };
foreach (var entry in entries)
{
hits[entry]++;
}
The elements in the hits array are automatically initialized to 0. When the foreach loop is complete, hits will contain the occurrence count for every number in entries. If any is greater than 1, you have dupes.

Getting the index of the largest integer in an array

I have an array of integers and I need to know the index of the largest number (not the actual value, just the index of whichever is highest).
However, if one or more indexes "tie" for the highest value, I need to have all of the indexes that share that high value.
I assume this function would need to return an array (since it could be one or more indexes), but I am not totally sure how to go about getting the more efficient solution.
If this is going to be a common thing you could write your own Extension. You should add some additional sanity/null checking but this will get you started:
Module Extensions
<System.Runtime.CompilerServices.Extension()> Function FindAllIndexes(Of T)(ByVal array() As T, ByVal match As Predicate(Of T)) As Integer()
''//Our return object
Dim Ret As New List(Of Integer)
''//Current array index
Dim I As Integer = -1
''//Infinite loop, break out when we no more matches are found
Do While True
''//Loop for a match based on the last index found, add 1 so we dont keep returning the same value
I = System.Array.FindIndex(array, I + 1, match)
''//If we found something
If I >= 0 Then
''//Append to return object
Ret.Add(I)
Else
''//Otherwise break out of loop
Exit Do
End If
Loop
''//Return our array
Return Ret.ToArray()
End Function
End Module
Then to call it:
Dim ints As Integer() = New Integer() {1, 2, 8, 6, 8, 1, 4}
Dim S = ints.FindAllIndexes(Function(c) c = ints.Max())
''//S now holds 2 and 4
If you are using .NET 3.5, you can use the Max() Extension function to easily find the highest value, and use Where to locate the matching records in your source array.
IList has an IndexOf member, which helps. This code is completely untested, and probably has at least one off-by-one error.
Public Function GetPostionsOfMaxValue(ByVal input() As Integer) As Integer()
Dim ints = New List(Of Integer)(input)
Dim maxval = ints.Max
Dim indexes As New List(Of Integer)
Dim searchStart As Integer = 0
Do Until searchStart >= ints.Count
Dim index = ints.IndexOf(maxval, searchStart)
If index = -1 Then Exit Do
indexes.Add(index)
searchStart = index + 1
Loop
Return indexes.ToArray
End Function

VB.NET Array/Hashtable Issue

I am trying to make an array of hashtables. I don't know if this is the best solution, in PHP I would just do a multi-dim array, but it's not so easy in .NET. I am pretty new o VB, so if there is a better solution for this please explain.
I have 2 emails fields for a contact, and a contact can have many. I just want to load in the first two on the edit page for editing, whatever they may be.
Private Sub loadPrimaryContactEmails(ByVal db As CRMDataDataContext, ByVal contactID As Guid)
Dim q = (From ce In db.ContactEmails Where ce.ContactID = contactID Select ce).Take(2)
Dim Emails As Array
Dim count = 0
For Each email In q
Emails(count) = New Hashtable
Emails(count).Add("email", email.Email)
Emails(count).Add("label", email.Label)
Emails(count).Add("id", email.ContactEmailID)
count = count + 1
Next
txtPCEmail1.Text = Emails(0).Item("email")
txtPCEmail1Label.Text = Emails(0).Item("label")
lblEmail1ID.Text = Emails(0).Item("id")
txtPCEmail2.Text = Emails(1).Item("email")
txtPCEmail2Label.Text = Emails(1).Item("label")
lblEmail2ID.Text = Emails(1).Item("id")
End Sub
I get the error the first time I try to reference my array:
txtPCEmail1.Text = Emails(0).Item("email")
The error is:
Object variable or With block variable not set.
It builds, so I thought it might work. I can't just loop through my datasource because I have to explicitly set textbox fields. Is there a better way to go about doing this? Or is there a way to make an array of hashtables work?
EDIT - here is the good code:
So I went w/ the HybridDictionary...
Private Sub loadPrimaryContactEmails(ByVal db As CRMDataDataContext, ByVal contactID As Guid)
Dim q = (From ce In db.ContactEmails Where ce.ContactID = contactID Select ce).Take(2)
Dim Emails As New HybridDictionary()
Dim count = 1
For Each email In q
Emails.Add("email" + NCStr(count), email.Email)
Emails.Add("label" + NCStr(count), email.Label)
Emails.Add("id" + NCStr(count), email.ContactEmailID)
count = count + 1
Next
txtPCEmail1.Text = Emails("email1")
txtPCEmail1Label.Text = Emails("label1")
lblEmail1ID.Text = Emails("id1")
txtPCEmail2.Text = Emails("email2")
txtPCEmail2Label.Text = Emails("label2")
lblEmail2ID.Text = Emails("id2")
End Sub
SO yeah, kind of a hack, but I don't feel like I should have to making special methods just to load some data into a dictionary or array or whatever.
Arrays in VB.NET are different than in PHP. You will need to define the size of your array before attempting to set elements of the array.
Better yet, consider using the generic List<T> collection.
Yes Phil is right you haven't specified the Initial Size of the Array.
And as suggested by him Use generic list or I would recommend
"System.Collections.Specialized.StringCollection" Class or "System.Collections.Specialized.HybridDictionary" class
Build the hashtable first and then build the array.
Dim hash As New Hashtable()
hash.Add("Header", shortModel)
hash.Add("SpecInfo", specinfo)
hash.Add("SerialNumber", serie & "-L")
hash.Add("SerialNumber2", serie)
hash.Add("seriel", serie & "-L")
hash.Add("serie", serie)
hash.Add("Product", modelBase)
hash.Add("varBC", bc)
hash.Add("box_id", boxId.Substring(4).ToString)
Dim dt As DataTable = DbUtil.GetCursor("SFISM4.PKG_AGENCY.sp_get_print_param", {New OracleParameter("in_serie", "3CE5151ZW4")})
For Each row As DataRow In dt.Rows
hash.Add(row("NAME"), row("VALUE"))
Next
Dim mArray(hash.Count() - 1, 1) As String
Dim i As Integer = 0
For Each row As DictionaryEntry In hash
mArray(i, 0) = row.Key.ToString()
mArray(i, 1) = row.Value.ToString()
i = i + 1
Next

Array intersection function speed

I've written a short function for array intersection and wanted to know why one function is faster than the other.
1)
Dim list2() As String 'Assume it has values'
Dim list2length As Integer = list2.length
Function newintersect(ByRef list1() As String) As String()
Dim intersection As New ArrayList
If (list1.Length < list2length) Then
'use list2'
For Each thing As String In list2
If (Array.IndexOf(list1, thing) <> -1) Then
intersection.Add(thing)
End If
Next
Else
'use list1'
For Each thing As String In list1
If (Array.IndexOf(list2, thing) <> -1) Then
intersection.Add(thing)
End If
Next
End If
Return intersection
End Function
2)
Dim list2() As String 'Assume it has values'
Dim list2length As Integer = list2.length
Function newintersect(ByRef list1() As String) As String()
Dim intersection As New ArrayList
If (list1.Length > list2length) Then 'changed >'
'use list2'
For Each thing As String In list2
If (Array.IndexOf(list1, thing) <> -1) Then
intersection.Add(thing)
End If
Next
Else
'use list1'
For Each thing As String In list1
If (Array.IndexOf(list2, thing) <> -1) Then
intersection.Add(thing)
End If
Next
End If
Return intersection
End Function
3)
Dim list2() As String 'Assume it has values'
Dim list2length As Integer = list2.length
Function newintersect(ByRef list1() As String) As String()
For Each thing As String In list1
If (Array.IndexOf(list2, thing) <> -1) Then
intersection.Add(thing)
End If
Next
Return intersection
End Function
So for my testcase, 1 take 65 seconds, 3 takes 63 seconds, while 2 actually takes 75 seconds. Anyone know why 3 is the fastest? And why is 1 faster than 2?
(Sorry about the poor formatting...can't seem to paste it right)
That's not much of a difference. Also, it doesn't seem like the methods would produce the same result, so it would be pointless to compare the performance, right?
Anyhow, the Array.IndexOf is not very efficient way to find items, and doesn't scale well. You should get a dramatic improvement if you use a hash key based collection as lookup instead, something like this:
Function newintersect(ByRef list1 As String(), ByRef list2 As String()) As String()
Dim smaller As HashSet(Of String)
Dim larger As String()
If list1.Length < list2.Length Then
smaller = New HashSet(Of String)(list1)
larger = list2
Else
smaller = New HashSet(Of String)(list2)
larger = list1
End If
Dim intersection As New List(Of String)
For Each item As String In larger
If smaller.Contains(item) Then
intersection.Add(item)
End If
Next
Return intersection.ToArray()
End Function
I'd expect you'd find that with different test cases you can reverse the results you had above and reach a situation where 2 is fastest and 1 & 3 are slower.
It's difficult to comment without knowing the make-up of the test case, it'll depend on the location of 'intersecting' items within the two arrays - if these tend to be close the to front on one array and closer to the end of another then the nesting order of the array iteration / IndexOf will have markedly different performance.
BTW - there are better ways of performing an intersection - sorting one or other array and performing a BinarySearch is one means - using a Dictionary(Of String, ...) or similar is another - and either would result in far better performance.
This is from the MSDN documentation
Dim id1() As Integer = {44, 26, 92, 30, 71, 38}
Dim id2() As Integer = {39, 59, 83, 47, 26, 4, 30}
' Find the set intersection of the two arrays.
Dim intersection As IEnumerable(Of Integer) = id1.Intersect(id2)
For Each id As Integer In intersection
Debug.WriteLine(id.ToString)
Next