Number statics VB.NET - vb.net

I'm trying to make a program which will be able to add 10 random numbers in a list. After this you have the possibility to see what the lowest,highest, avarage and median numbers are.
Public Class number
Private _numbers As List(Of Integer)
Public Property numbers() As List(Of Integer)
Get
Return _numbers
End Get
Set(ByVal value As List(Of Integer))
_numbers= value
End Set
End Property
Public Function addnumber() As Integer
Dim rnd As New Random
For teller As Integer = 0 To 9
_numbers(teller) &= rnd.Next(0, 1001)
Next
Return _numbers.Sort
End Function
End Class
At the end of the code (Return _numbers.Sort) it says expression does not produce a value.
Any tips to fix this?

There are a number of issues with your code.
First, to answer your question: look at the documentation of List.Sort. It doesn’t return a value. It sorts the list in-place.
Next, you cannot use &= with a list of integers in the following line:
_numbers(teller) &= rnd.Next(0, 1001)
If this code compiles without complaint, then you need to enable Option Strict in the project settings (and do it globally, for good measure). &= is a string concatenation operator.
Next, your code attempts to overwrite items in the list, but you never specified that the list should have 10 items. Hence, this will fail at runtime with an ArgumentOutOfRangeException. You need to Add the items to the list — again, refer to the documentation.

Related

How to randomly select strings vb.net

Is there a simple solution to select random strings in vb.net? I have a list of about twenty paragraphs where three need to go after each other and I want it to be random. Do I have to create a variable? Or is there a command that can be run on a button click?
One (fairly easy way) to accomplish this would be to have a collection of the paragraphs you want to use, and then use PeanutButter.RandomValueGen from the Nuget package PeanutButter.RandomGenerators (it's open-source too)
RandomValueGen.GetRandomFrom takes a collection of anything and returns a random item from the collection. As a bonus, you can specify a params list of values not to pick, so you can ensure that your paragraphs aren't repeated.
Whilst the library is written in C#, it can obviously be used from any .NET project. There are a lot of other generator methods on RandomValueGen too, if you're interested.
Full disclosure: I'm the author.
If you have a normal list, this should work:
If not, write what kind of list you have.
Dim rn As New Random
Dim selct As String = lst(rn.Next(0, lst.Count - 1))
selct is the output.
Replace lst with your list name.
if you don't want to have a dependency or need to stay on 4.0 for some odd reason or reason X, you can always try this instead
Private rnd As New Random
Public Function GetRandom(input As IEnumerable(Of String), itemToGet As Integer) As List(Of String)
If input.Count < itemToGet Then
Throw New Exception("List is too small")
End If
Dim copy = input.ToList
Dim result As New List(Of String)
Dim item As Integer
While itemToGet > 0
item = rnd.Next(0, copy.Count)
result.Add(copy(item))
copy.RemoveAt(item)
itemToGet -= 1
End While
Return result
End Function

Checking 3rd character with Char.IsNumber in vb.net

I am searching a database and pulling results from it. Before displaying it in WPF I am checking the contents of the text in a field called PrimarySponsor which can be (1) blank/null (2) number at 3rd character (3) persons name. I am currently using Char.IsNumber to check option 2 if there is a number at position 4.
If reader("PrimarySponsor") Is DBNull.Value Then
resultxPrimSpon = ""
ElseIf Char.IsNumber(reader("PrimarySponsor"), 3) Then
resultxPrimSpon = "Terminated"
Else
resultxPrimSpon = reader("PrimarySponsor")
End If
Before I put the Char.IsNumber check in I was getting 4 results displaying. When i add the Char.IsNumber code I only get 2 results along with the error;
Error while connecting to SQLServer.Sepcified argument was out of the range of valid values. Parameter name: index.
Anyone have any ideas about why this is happening or how to work around it?
It's not clear where you get that error because Char.IsNumber is not a sql-server method. So i assume that it's a custom message from you. However, the "Specified argument was out of the range" is documented:
ArgumentOutOfRangeException: index is less than zero or greater than
the last position in s.
So it seems that at least one of the strings is shorter than 4 characters. In general you should store the reader values in a variable of the correct type if you have to access it more than once. In this case in a String-variable.
But it's also a good idea to create a custom type that has all properties. Then you can add all to a List(Of T). Here's an example:
Public Class Sponsor
Public Property PrimarySponsor As String
End Class
Of course you could also fill a List(Of String) instead of a List(Of Sponsor). Then you don't need to create a new type. But i assume that you have more than one column in the table. Using a custom type increases readability and maintainability much.
....
Dim allSponsors As New List(Of Sponsor)
Using reader = command.ExecuteReader()
If reader.HasRows Then
Dim primSponsorColumnIndex = reader.GetOrdinal("PrimarySponsor")
While reader.Read
Dim sponsor As New Sponsor()
If reader.IsDBNull(primSponsorColumnIndex) Then
sponsor.PrimarySponsor = ""
Else
sponsor.PrimarySponsor = reader.GetString(primSponsorColumnIndex)
If sponsor.PrimarySponsor.Length >= 4 AndAlso _
Char.IsDigit(sponsor.PrimarySponsor(3)) Then
sponsor.PrimarySponsor = "Terminated"
End If
End If
allSponsors.Add(sponsor)
End While
End If
End Using
First use DataReader.IsDBNull to check if the value is Null. Then check if Length >= 4 before you use Char.IsDigit(sponsor.PrimarySponsor(3)) to avoid the ArgumentOutOfRangeException.
Difference between Char.IsDigit() and Char.IsNumber() in C#

Sorting a SortedDictionary by key length in Visual Basic?

I'm writing a script that anonymizes participant data from a file.
Basically, I have:
A folder of plaintext participant data (sometimes CSV, sometimes XML, sometimes TXT)
A file of known usernames and accompanying anonymous IDs (e.g. jsmith1 as a known username, User123 as an anonymous ID)
I want to replace every instance of the known username with the corresponding anonymous ID.
Generally speaking, what I have works just fine -- it loads in the usernames and anonymous IDs into a dictionary and one by one runs a find-and-replace on the document text for each.
However, this script also strips out names, and it runs into some difficulty when it encounters names contained in other names. So, for example, I have two pairs:
John,User123
Johnny,User456
Now, when I run the find-and-replace, it may first encounter John, and as a result it replaces Johnny with User123ny, and then doesn't trigger Johnny.
The simplest solution I can think of is just to run the find-and-replace from longest key to shortest. To do that, it looks like I need a SortedDictionary.
However, I can't seem to convince Visual Basic to take my custom Comparer for this. How do you specify this? What I have is:
Sub Main()
Dim nameDict As New SortedDictionary(Of String, String)(AddressOf SortKeyByLength)
End Sub
Public Function SortKeyByLength(key1 As String, key2 As String) As Integer
If key1.Length > key2.Length Then
Return 1
ElseIf key1.Length < key2.Length Then
Return -1
Else
Return 0
End If
End Function
(The full details above are in case anyone has any better ideas for how to resolve this problem in general.)
I think it takes a class that implements the IComparer interface, so you'd want something like:
Public Class ByLengthComparer
Implements IComparer(Of String)
Public Function Compare(key1 As String, key2 As String) As Integer Implements IComparer(Of String).Compare
If key1.Length > key2.Length Then
Return 1
ElseIf key1.Length < key2.Length Then
Return -1
Else
'[edit: in response to comments below]
'Return 0
Return key1.Compare(key2)
End If
End Function
End Class
Then, inside your main method, you'd call it like this:
Dim nameDict As New SortedDictionary(Of String, String)(New ByLengthComparer())
You might want to take a look (or a relook) at the documentation for the SortedDictionary constructor, and how to make a class that implements IComparer.

Dictionary returning same value for every key only when value is also an enumerable or custom

i am a noob, so please take this question with that in mind. Here is very simple piece of code:
Sub main()
{
Dim m_Dictionary as new Dictionary(Of Integer, List(Of String))
Dim workingList as new List(Of String)
Dim workingKey as Integer
Dim keyStash as List(Of Integer)
Dim workingDict as new Dictionary(Of Integer, String)
For i=0 to 9
Do
workingKey = RandomInteger()
Loop While workingList.ContainsKey(workingKey)
For n=0 to 4
workingList.Add(RandomString())
Next
keyStash.Add(workingKey)
workingDict.Add(workingKey, workingList)
Next
' now I just want to play back the generators of random data
For each Key As Integer in keyStash
For each Entry as String in workingDict(Key).Value
Line(Entry)
Next
Next
Instead of everything playing back nicely as one might expect, I am left with a fully accurate stash of keys for the dictionary. However, the values for strings inside each list instance are ALL THE SAME FOR EVERY KEY. Those values are equal to the values in the last loop of random data generation. So instead of playing back 50 uniques entries, it writes out 9 times the last loop. I looked inside - everything looks good. Get this. All lists, collections, hash-tables, all of iterated types and also custom types demonstrate this behavior. I found the solution, but it does not explain anything. Can anyone help explaining this, please!??
The variable that keeps the strings generated by RandomString is created outside the loop. Inside that loop you add continuosly new strings to the same instance and add the same list instance to every new integer key. At the end of the loop every integer key added has its value pointing to the same reference of the list. Of course they are identical....
A first fix to your code could be
Dim m_Dictionary as new Dictionary(Of Integer, List(Of String))
Dim workingKey as Integer
For i=0 to 9
' Internal to the loop. so at each loop you get a new list
' to use for the specific key generated in the current loop
Dim workingList as new List(Of String)
Do
workingKey = RandomInteger()
Loop While m_Dictionary.ContainsKey(workingKey)
For n=0 to 4
workingList.Add(RandomString())
Next
m_Dictionary.Add(workingKey, workingList)
Next
For each k in m_Dictionary
For each Entry in k.Value
' Line(Entry)
Console.WriteLine("Key=" & k.Key & " Values = " & Entry)
Next
Next
Please, remember to use Option Strict ON, the current code treats quietly strings as if they were numbers, and this is not a good practice. Option Strict ON will force you to think twice when you work with different type of data.

VB - How do you remove "empty" items from a generic list?

I have a VB.NET (2010) project that contains a generic list, and I'm trying to figure out how to remove any "empty" items from the list. When I say "empty", I mean any item that does not contain any actual characters (but it may contain any amount of whitespace, or no whitespace at all).
For example, let's say this is my list...
Dim MyList As New List(Of String)
MyList.Add("a")
MyList.Add("")
MyList.Add("b")
MyList.Add(" ")
MyList.Add("c")
MyList.Add(" ")
MyList.Add("d")
I need it so that if I did a count on that list, it would return 4 items, instead of 7. For example...
Dim ListCount As Integer = MyList.Count
MessageBox.Show(ListCount) ' Should show "4"
It would be nice if there was something like...
MyList.RemoveEmpty
Anyways... I've been searching Google for a solution to this for the past few hours, but haven't been able to turn up anything so far. So... any ideas?
BTW, I'm targeting the .NET 2.0 framework for this project.
Thanks in advance!
You can use List.RemoveAll
MyList.RemoveAll(Function(str) String.IsNullOrWhiteSpace(str))
If you don't use at least .NET 4, you can't use String.IsNullOrWhiteSpace. Then you can implement the method yourself:
Public Shared Function IsNullOrWhiteSpace(value As String) As Boolean
If value Is Nothing Then
Return True
End If
For i As Integer = 0 To value.Length - 1
If Not Char.IsWhiteSpace(value(i)) Then
Return False
End If
Next
Return True
End Function
Note that Char.IsWhiteSpace is there since 1.1.
The post marked as solution didn't works for me.
Try this:
MyList.AsEnumerable().Where(Function (x) Not String.IsNullOrEmpty(x)).ToList
This must returns you a list without empty values.