I am using the following:
return string.Join(\"\\n\", parts);
Parts has 7 entries but two of them are the empty string \"\". How can I fi
Try it using 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);
or
return string.Join("\n", hello.Where(x => x.Trim().Length != 0));
To do it in .NET 2.0 (no LINQ), e.g. for ReportingServices without writing a function for it:
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)
This assumes that the character backspace doesn't occur in your strings (should usually be true, because you can't simply enter this character by keyboard).
An alternate way of doing this is by using 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));
This gives:
The,quick,brown,fox,is,here
@Stefan Steiger:
string yourString = "echo 'foo' | sed '/foo/d;'";
This gives:
echo 'foo' , sed '/foo/d;'
Which is as I would expect. See the dotnetfiddle of it.
You can use Where
in LINQ to select strings which are not empty:
return string.Join("\n", parts.Where(s => !string.IsNullOrEmpty(s)));