Finding lowest value in List of tuple in VB.Net - vb.net

I am trying to find lowest Item2 and return Item1 from tuple list, I tried to do it with List.Min but I couldn't get it right, here is my code.
Dim ahlist As New List(Of Tuple(Of String, Double))
ahlist.Add(Tuple.Create("test1", 1.2))
ahlist.Add(Tuple.Create("test2", 0.2))
ahlist.Add(Tuple.Create("test3", 1.8))
Basically I want to find lowest number and return string (test2) in this case.

I'd recommend using a different data structure for this:
https://msdn.microsoft.com/en-us/library/ms132329(v=vs.110).aspx
You add the key/value combinations. The 0th one in the list is always the minimum key, making its an O(1) operation instead of O(n). In this case, the key would be the Decimal, and the value would be the string.

You can reverse the order of the items for the comparison to be by the number first:
Dim ahlist As New List(Of Tuple(Of Double, String))
ahlist.Add(Tuple.Create(1.2, "test1"))

Just a simple fix from C# syntax to VB.net to #Aamir Nakehwa's answer.
Dim minValue As Double = ahlist.Min(Function(x) x.Item2)
Debug.Print(minValue.ToString)

ahlist.Min(x => x.Item2)
Try this. I will return you the minimum value from your tuple list.
And hold it in any variable to use like below
Dim minValue as Double = ahlist.Min(Function(x) x.Item2)

Related

Linq aggregate from Dictionary

I have a dictionary of T, and i want to get the multiplication of a range of the collection based on a predicate
In particular i have a Dictionary Of Key (String) with an Average (integer) and Data (integer)
I want to multiplicate the Data of all Elements that have an Average > 6
Class Classroom
Sub New(ByVal NewData As Integer, ByVal NewAverage As Integer)
Average = NewAverage
Data = NewData
End Sub
Dim Data As Integer
Dim Average As Integer
End Class
Dim Elements As New Dictionary(Of String, Classroom)
Elements.Add("Simon", New Classroom( 6, 5))
Elements.Add("Jennifer", New Classroom(7, 7))
Elements.Add("Timoty", New Classroom(8, 4))
Elements.Add("Janet", New Classroom(7, 6))
I tried this Linq expression, but it doesn't works
Dim Result as Integer = Elements.Where(Function(minAverage) minAverage.Value.Average > 6).Aggregate(Fuction(x, y) x.Value.Data * y.Value.Data)
The Aggregate function returns a single, aggregated, object of the same type as all the other items in the list. In other words, if you use Aggregate on a list of persons, it will return a person. If you use it on a list of animals, it will return an animal. Etc. Since you are using it on a Dictionary(Of String, Classroom), which is a list of KeyValuePair(Of String, Classroom), that means the aggregate will be of that type, not an Integer, as your code is expecting.
To make it work properly, you need to do one of two things. Either you need to fix the lambda in your Aggregate function so that it returns a KeyValuePair(Of String, Classroom) (and fix the Result variable as well), or you need to add a Select method to transform the list into something simpler before calling Aggregate. Since you aren't using any of the other data in the list in the aggregating lambda it seems like the latter is the more appropriate approach. So, for instance:
Dim Result As Integer = Elements.
Where(Function(pair) pair.Value.Average > 6).
Select(Function(pair) pair.Value.Data).
Aggregate(Function(x, y) x * y)

vb.net Pair Combinations to Create All Possible Sets

I need help figuring out how to go about programming this problem. I have an unknown number of pairs. Each pair is a Length x Width. I want to create sets of every possible combination of either a Length or Width from each pair. Here is an example of what I'm trying to do:
If I input 3 pairs, (1x2) (3x4) (5x6) I would get the following sets:
(1,3,5) (1,3,6) (1,4,5) (1,4,6) (2,3,5) (2,3,6) (2,4,5) (2,4,6)
So if I had 4 pairs, it would create a total of 16 sets, etc. I need to be able to input each pair and after all pairs have been entered, I need it to print out the sets. It can never include both numbers from a given pair in the same set. How do I create a loop or is there a built in math function that could produce all possible sets from a given number of pair inputs? I hope I described the problem well enough but if not, please ask questions. Thanks
This is called Cartesian product.
For example, if we have two sets A and B, such that
A = {1,2}
B = {3,4}
Then the result of the Cartesian product A x B is equal to
A x B = {(1,3),(1,4),(2,3),(2,4)}
If now we want to make the Cartesian product between the result obtained above and a new set, for example:
N = {5,6}
The result of the Cartesian product A x B x N, is equal to
A x B = {(1,3),(1,4),(2,3),(2,4)}
N = {5,6}
──────────────────────────────────────────────────
A x B x N = {(1,3,5),(1,3,6),(1,4,5),(1,4,6),(2,3,5),(2,3,6),(2,4,5),(2,4,6)}
Each element of the first set must be paired with each element of the second set.
I have developed 4 solutions to the Cartesian product:
Using a mathematical model, but without recursion. This solution
vectors using calculating for each combination number.
Using recursion, with the Collections class.
using the List (Of ...) class, also with recursion.
These three solutions seemed to me difficult to explain to you.
Furthermore, it is very difficult for me to explain my thoughts in English, because my native language is Castilian.
So I made the effort to create another solution that does not use recursion, which was more simple and friendly for any programmer.
Finally, I could create a satisfactory solution. Easy to understand and without recursion.
It is also very versatile. Any number of sets is accepted, as required, from 2 onwards.
You can also use any number of items. This depends on the requirements of each developer.
I hope this 4th. solution I devised, will please you, esteemed colleagues.
Only need a ListBox1 within Form4. Here it is:
Public Class Form4
Private Sub Form4_Load(sender As System.Object, e As System.EventArgs) Handles MyBase.Load
'┌─────────── Temporary code for example ───────────┐
Dim Set_1 As List(Of String) = New List(Of String)
Dim Set_2 As List(Of String) = New List(Of String)
Dim Set_3 As List(Of String) = New List(Of String)
Set_1.Add("1")
Set_1.Add("2")
Set_2.Add("3")
Set_2.Add("4")
Set_3.Add("5")
Set_3.Add("6")
'└──────────────────────────────────────────────────┘
Dim Sets As List(Of Object) = New List(Of Object)
Sets.Add(Set_1)
Sets.Add(Set_2)
Sets.Add(Set_3)
Dim product As List(Of String) = Sets(0)
For i = 1 To Sets.Count - 1
product = CartesianProduct(product, Sets(i))
Next
For Each element As String In product
Me.ListBox1.Items.Add(element)
Next
End Sub
Private Function CartesianProduct(ByVal Set_A As List(Of String), ByVal Set_B As List(Of String)) As List(Of String)
Dim product As List(Of String) = New List(Of String)
For Each a As String In Set_A
For Each b As String In Set_B
product.Add(a & b)
Next
Next
Return product
End Function
End Class
Have a nice day! :)

Store a two value combination

I want to store a two value combination but cannot find the right class. I know I could do it with a two dimentional array but is there another way since I always have to do the redimentionalisation. I know about the dictionary but there is the first value always the key.
Example:
I have a dgv and want to collect the rownumbers with duplicates. I iterate throu the dgv and collect 1 and 4, 20 and 33 and so on and store this combinations to use them somewhere else.
You can use collection of Tuple. For example :
Dim tuples As New List(Of Tuple(Of Integer, Integer))
tuples.Add(Tuple.Create(1, 4))
tuples.Add(Tuple.Create(20, 33))
One way would be with a Dictionary(Of DataGridViewRow, List(Of Integer)). The list would contain the rows holding the values in the key. This will work if you get more than 2 rows trhat are duplicates.

Simplest/fastest way to check if value exists in DataTable in VB.net?

I have a DataTable (currently with multiple columns but I could just grab one column if it makes it easier). I want to check if a String value exists in a column of the DataTable. (I'm doing it many times so I want it to be reasonably fast.)
What is a good way to do this? Iterating through the DataTable rows each time seems like a bad way. Can I convert the column to a flat List/Array format, and use a built in function? Something like myStrList.Contains("value")?
You can use select to find whether that value exist or not. If so, it returns rows or it will not. Here is some sample code to help you.
Dim foundRow() As DataRow
foundRow = dt.Select("SalesCategory='HP'")
If the data in your DataTable doesn't change very often, and you search the DataTable multiple times, and your DataTable contains many rows, then it's likely going to be a lot faster to build your own index for the data.
The simplest way to do this is to sort the data by the key column so that you can then do a binary search on the sorted list. For instance, you can build an index like this:
Private Function BuildIndex(table As DataTable, keyColumnIndex As Integer) As List(Of String)
Dim index As New List(Of String)(table.Rows.Count)
For Each row As DataRow in table.Rows
index.Add(row(keyColumnIndex))
Next
index.Sort()
Return index
End Function
Then, you can check if a value exists in the index quickly with a binary search, like this:
Private Function ItemExists(index As List(Of String), key As String) As Boolean
Dim index As Integer = index.BinarySearch(key)
If index >= 0 Then
Return True
Else
Return False
End If
End Function
You could also do the same thing with a simple string array. Or, you could use a Dictionary object (which is an implementation of a hash table) to build a hash index of your DataTable, for instance:
Private Function BuildIndex(table As DataTable, keyColumnIndex As Integer) As Dictionary(Of String, DataRow)
Dim index As New Dictionary(Of String, DataRow)(table.Rows.Count)
For Each row As DataRow in table.Rows
index(row(keyColumnIndex)) = row
Next
Return index
End Function
Then, you can get the matching DataRow for a given key, like this:
Dim index As Dictionary(Of String, DataRow) = BuildIndex(myDataTable, myKeyColumnIndex)
Dim row As DataRow = Nothing
If index.TryGetValue(myKey, row) Then
' row was found, can now use row variable to access all the data in that row
Else
' row with that key does not exist
End If
You may also want to look into using either the SortedList or SortedDictionary class. Both of these are implementations of binary trees. It's hard to say which of all of these options is going to be fastest in your particular scenario. It all depends on the type of data, how often the index needs to be re-built, how often you search it, how many rows are in the DataTable, and what you need to do with the found items. The best thing to do would be to try each one in a test case and see which one works best for what you need.
You should use row filter or DataTable.Rows.Find() instead of select (select does not use indexes). Depending on your table structure, specifically if your field in question is indexed (locally), performance of either way should be much faster than looping through all rows. In .NET, a set of fields needs to be a PrimaryKey to become indexed.
If your field is not indexed, I would avoid both select and row filter, because aside from overhead of class complexity, they don't offer compile time check for correctness of your condition. If it's a long one, you may end up spending lots of time debugging it once in a while.
It is always preferable to have your check strictly typed. Having first defined an underlying type, you can also define this helper method, which you can convert to extension method of DataTable class later:
Shared Function CheckValue(myTable As DataTable, columnName As String, searchValue As String) As Boolean
For row As DataRow In myTable.Rows
If row(columnName) = searchValue Then Return True
Next
Return False
End Function
or a more generic version of it:
Shared Function CheckValue(myTable As DataTable, checkFunc As Func(Of DataRow, Boolean)) As Boolean
For Each row As DataRow In myTable.Rows
If checkFunc(row) Then Return True
Next
Return False
End Function
and its usage:
CheckValue(myTable, Function(x) x("myColumn") = "123")
If your row class has MyColumn property of type String, it becomes:
CheckValue(myTable, Function(x) x.myColumn = "123")
One of the benefits of above approach is that you are able to feed calculated fields into your check condition, since myColumn here does not need to match a physical myColumn in the table/database.
bool exists = dt.AsEnumerable().Where(c => c.Field<string>("Author").Equals("your lookup value")).Count() > 0;

Pick a random number from a set of numbers

I have an array of integers like these;
dim x as integer()={10,9,4,7,6,8,3}.
Now I want to pick a random number from it,how can I do this in visual basic?Thanks in advance...
First you need a random generator:
Dim rnd As New Random()
Then you pick a random number that represents an index into the array:
Dim index As Integer = rnd.Next(0, x.Length)
Then you get the value from the array:
Dim value As Integer = x(index)
Or the two last as a single statement:
Dim value As Integer = x(rnd.Next(0, x.Length))
Now, if you also want to remove the number that you picked from the array, you shouldn't use an array in the first place. You should use a List(Of Integer) as that is designed to be dynamic in size.
randomly choose an index from 0 to length-1 from your array.