Language: C# 4.0
There is a List<string> with values Value1, Value2, Value3 and so on.
I would like to perform a join on the generic List so that the output should be
string values = "Value1, Value2 and Value3";
and if there is only one value
string values = "Value1";
I am currently replacing LastIndexOf , with and. But did not like that much.
Whats the most efficient method to join like this?
You can use the
String.Join(string glue, string[] array);function for this.Hope that helps. (Note:
myListis the List you already have in your application somewhere.)Update: Noticed your and requirement a little too late, my appologies, here is a little update:
Alternatively (or maybe even better) you can use a
StringBuilderfor this, instead of string concatenation. (Remember: You will still have to check if you have only one value in the list.)Update: Here is a simple extension method.
And one can call it like