6

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!

4

1 回答 1

19

您可以使用List.RemoveAll

MyList.RemoveAll(Function(str) String.IsNullOrWhiteSpace(str))

如果您至少不使用 .NET 4,则不能使用String.IsNullOrWhiteSpace. 然后您可以自己实现该方法:

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

请注意,Char.IsWhiteSpace自 1.1 以来就存在。

于 2012-10-11T22:35:22.670 回答