VB - 你如何删除“空"?通用列表中的项目? [英] VB - How do you remove "empty" items from a generic list?

查看:22
本文介绍了VB - 你如何删除“空"?通用列表中的项目?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个包含通用列表的 VB.NET (2010) 项目,我正在尝试弄清楚如何从列表中删除任何空"项目.当我说空"时,我的意思是任何不包含任何实际字符的项目(但它可能包含任意数量的空格,或者根本没有空格).

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")

我需要它,以便如果我对该列表进行计数,它将返回 4 个项目,而不是 7 个.例如...

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?

顺便说一句,我的目标是该项目的 .NET 2.0 框架.

BTW, I'm targeting the .NET 2.0 framework for this project.

提前致谢!

推荐答案

您可以使用 List.RemoveAll

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

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

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

请注意 Char.IsWhiteSpace 从 1.1 开始就有了.

Note that Char.IsWhiteSpace is there since 1.1.

这篇关于VB - 你如何删除“空"?通用列表中的项目?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆