Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Building a string from List<string> in C#

Tags:

c#

list

The List<string> has ("ABC","","DEF","","XYZ"), how can I get the string "ABC::DEF::XYZ" out of the List in C#?

ADDED

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?

like image 726
prosseek Avatar asked May 23 '26 00:05

prosseek


1 Answers

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);
like image 155
Ani Avatar answered May 24 '26 16:05

Ani



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!