The List<string> has ("ABC","","DEF","","XYZ"), how can I get the string "ABC::DEF::XYZ" out of the List in C#?
List<string> strings = new List<string> {"ABC","","DEF","","XYZ"};
string joined = string.Join("::", strings.ToArray());
Console.WriteLine(joined);
gives ABC::::DEF::::XYZ, not ABC::DEF::XYZ, how can one skip the empty strings ("") in a list?
You can do:
List<string> strings = ...
string joined = string.Join(":", strings.ToArray());
In .NET 4.0, you can leave out the ToArray() call.
EDIT: Based on your update that indicates that you want to skip empty strings and use two colons as the delimiter, you can do:
// Use !string.IsNullOrEmpty or !string.IsNullOrWhiteSpace if more appropriate.
string[] filtered = list.Where(s => s != string.Empty)
.ToArray();
string joined = string.Join("::", filtered);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With