我正在使用以下内容:
return string.Join("\n", parts);
Parts 有 7 个条目,但其中两个是空字符串“”。我怎样才能先删除这两个条目,然后加入剩下的五个?
您可以Where
在 LINQ 中使用来选择不为空的字符串:
return string.Join("\n", parts.Where(s => !string.IsNullOrEmpty(s)));
另一种方法是使用 StringSplitOptions.RemoveEmptyEntries:
例如
string yourString = "The|quick||brown|||fox|is|here";
char[] delimiter = new char[] { '|' };
string result = string.Join(",", yourString.Split(delimiter, StringSplitOptions.RemoveEmptyEntries));
这给出了:
快,棕色,狐狸,是,在这里
@Stefan Steiger:
string yourString = "echo 'foo' | sed '/foo/d;'";
这给出了:
echo 'foo' , sed '/foo/d;'
这是我所期望的。请参阅它的 dotnetfiddle。
尝试使用LINQ
string[] hello = new string[] { "ads", "zxc", "wer", "", "wer", "", "243" };
string newString = string.Join("\n", hello.Where(x => x.Trim().Length != 0));
MessageBox.Show(newString);
或者
return string.Join("\n", hello.Where(x => x.Trim().Length != 0));
要在 .NET 2.0(无 LINQ)中执行此操作,例如针对 ReportingServices 而无需为其编写函数:
C#
string a = "", b = "b", c = "", d = "d", e = "";
string lala = string.Join(" / ",
string.Join("\u0008", new string[] { a, b, c, d, e }).Split(new char[] { '\u0008' }, System.StringSplitOptions.RemoveEmptyEntries)
);
System.Console.WriteLine(lala);
VB.NET
Dim a As String = "", b As String = "b", c As String = "", d As String = "d", e As String = ""
Dim lala As String = String.Join(" / ", String.Join(vbBack, New String() {a, b, c, d, e}).Split(New Char() {ControlChars.Back}, System.StringSplitOptions.RemoveEmptyEntries))
System.Console.WriteLine(lala)
这假设您的字符串中没有出现退格字符(通常应该是正确的,因为您不能简单地通过键盘输入此字符)。