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

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.

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

Vb Net check if arrayList contains a substring

I am using myArrayList.Contains(myString) and myArrayList.IndexOf(myString) to check if arrayList contains provided string and get its index respectively.
But, How could I check if contains a substring?
Dim myArrayList as New ArrayList()
myArrayList.add("sub1;sub2")
myArrayList.add("sub3;sub4")
so, something like, myArrayList.Contains("sub3") should return True
Well you could use the ArrayList to search for substrings with
Dim result = myArrayList.ToArray().Any(Function(x) x.ToString().Contains("sub3"))
Of course the advice to use a strongly typed List(Of String) is absolutely correct.
As far as your question goes, without discussing why do you need ArrayList, because array list is there only for backwards compatibility - to select indexes of items that contain specific string, the best performance you will get here
Dim indexes As New List(Of Integer)(100)
For i As Integer = 0 to myArrayList.Count - 1
If DirectCast(myArrayList(i), String).Contains("sub3") Then
indexes.Add(i)
End If
Next
Again, this is if you need to get your indexes. In your case, ArrayList.Contains - you testing whole object [string in your case]. While you need to get the string and test it's part using String.Contains
If you want to test in non case-sensitive manner, you can use String.IndexOf

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#

Number statics 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.

How to restrict swear word input when using a textbox within Visual Basic

I have had several ideas yet most of the solutions online only restrict certain keys or only numbers, not full strings.
I want a solution that as soon as a keypress of a swear word has been inputted, VB detects it then disallows it. I have been able to do exact string matching so if a user puts the work F*** in, then it shows an error message, but this would not work if the user decided to put in "F***nugget". It would not be elegant nor time feasible to enter every possible combination of swear words. Thanks in advance for help.
If e.KeyChar = "F***" Then
SelectionTextBoxTeamName.Clear()
MessageBox.Show("Please choose something else")
You need a 'string contains' function.
If you're writing in vb.net try String's Contains function, which is used like this:
Dim b As Boolean
b = s1.Contains(s2)
If you're not writing in .net
try InStr function. You can use it as follows:
InStr("find the comma, in the string", ",")
EDIT: after op's comment
If you want to check several swears you can put them in an array and check for each:
Dim swears = {"F***", "S***"}
Dim hasSwears As Boolean = false
For Each swear As String In swears
If InStr(textBox.Text, swear) > 0 Then
hasSwears = true
End If
Next
Now you know if there are any swears according to hasSwears.