Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

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!

like image 901
NotQuiteThereYet Avatar asked Oct 11 '12 22:10

NotQuiteThereYet


1 Answers

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.

like image 75
Tim Schmelter Avatar answered Sep 23 '22 15:09

Tim Schmelter