Reputation: 190679
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?
Upvotes: 2
Views: 2434
Reputation: 113402
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);
Upvotes: 7
Reputation: 38200
I think you can have a look at The suggested method
post this you can simply do string.Join(",", strings.ToArray())
(replace the empty strings with ::)
Upvotes: 0
Reputation: 30705
string result = string.Join("::", list.Where(s => !string.IsNullOrEmpty(s)).ToArray());
Upvotes: 2
Reputation: 17499
string.Join("::", strings.Where(item=>!string.IsNullOrEmpty(item)).ToArray());
Upvotes: 1
Reputation: 128317
Using string.Join
with ToArray
would work.
As Ani said, if you're on .NET 4.0, you could leave out the ToArray
.
If you're not on .NET 4.0 but you don't want the overhead of the ToArray
call, you could write a method to create a StringBuilder
, append every item in the List<string>
plus your delimiter (skipping the delimiter after the last item), and return the result of ToString
at the end.
Upvotes: 0
Reputation: 6532
You should look at String.Join(), example String.Join(":",list.ToArray());
Upvotes: 0
Reputation: 532435
string.Join( ":", list )
in .NET 4.0. If you are using 3.5 or earlier, string.Join( ":", list.ToArray() )
Upvotes: 0