我使用以下内容:
return string.Join("\n", parts);
零件有7个条目,但其中两个是空字符串“”。如何首先删除这两个条目,然后加入剩下的五个?
答案 0 :(得分:25)
您可以在LINQ中使用Where
来选择非空的字符串:
return string.Join("\n", parts.Where(s => !string.IsNullOrEmpty(s)));
答案 1 :(得分:2)
另一种方法是使用StringSplitOptions.RemoveEmptyEntries:
e.g。
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;'
这正如我所料。 See the dotnetfiddle of it
答案 2 :(得分:1)
使用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));
答案 3 :(得分: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)
这假设字符退格不会出现在你的字符串中(通常应该是真的,因为你不能通过键盘输入这个字符)。