如何判断字符串数组中非空字符串的数量

Al *_*ndo -2 c# arrays string

我有一个管道分隔的字符串:

string line = "test|||tester||test||||||test test|"
Run Code Online (Sandbox Code Playgroud)

我正在读这个介绍一个字符串数组:

string[] wordsArr = line.Split(new string[] { "|" }, StringSplitOptions.None);
Run Code Online (Sandbox Code Playgroud)

如果框架内置了一种方法来查看数组中有多少项不为空,那么我的目标是无需手动编写循环.此外,我不能RemoveEmptyEntriesStringSplitOptionsb/c上使用物品,其中物品属于管道内的物质.

有任何想法吗?

gun*_*171 7

如果您要查找的只是计数,.Count请在拆分后使用.

string line = "test|||tester||test||||||test test|";

int notEmptyCount = line
    .Split('|')
    .Count(x => !string.IsNullOrEmpty(x));
Run Code Online (Sandbox Code Playgroud)

如果要过滤掉空的项目并访问剩余的所有项目,请.Where改用.

var notEmptyCollection = line
    .Split('|')
    .Where(x => !string.IsNullOrEmpty(x));
Run Code Online (Sandbox Code Playgroud)