16

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 first remove these two entries and then join the remaining five?

4 Answers 4

26

You can use Where in LINQ to select strings which are not empty:

 return string.Join("\n", parts.Where(s => !string.IsNullOrEmpty(s)));
Sign up to request clarification or add additional context in comments.

Comments

2

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.

2 Comments

Is Values a string like "foo|bar||baz|||baf"?
And now I enter a value like "echo 'foo' | sed '/foo/d;'" and it breaks horribly.
1

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

Comments

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.