Reputation: 263
Requirement is first,second,third,forth,fifth this work fine when I use string but it doesn't works when I use foreach
List<string> stringList = new List<string>();
stringList.Add("first");
stringList.Add("second");
stringList.Add("third");
stringList.Add("fourth");
stringList.Add("fifth");
string result = string.Join(", ", stringList).TrimEnd(',', ' ');
Console.WriteLine(result);
foreach (var item in stringList)
{
string resultt = string.Join(", ", item).TrimEnd(',', ' ');
Console.WriteLine(resultt);
}
I have to remove comma from last word from a List of string using foreach.
Upvotes: 1
Views: 1460
Reputation: 2008
If you consider the list as [first][,other][,other][,other] ... so we group the comma with the element after it, this becomes simple:
static String Join(string joiner, IEnumerable<String> list){
bool first = true;
StringBuilder sb = new StringBuilder();
foreach (s in list){
if(!first){
sb.Append(joiner);
}else{
first = false;
}
sb.Append(s);
}
return sb.ToString();
}
Upvotes: 1
Reputation: 850
You don't need the Trim() when joining list. You just have to do it this way.
string mergedString = string.Join(",", stringList.ToArray());
There won't be any comma in the beginning nor the end of the string.
Upvotes: 0
Reputation: 2332
The foreach loop iterates over each item in the list, so in your code resultt will always be equal to item. ie. resultt = item
I think you are trying to do this:
var resultt = "";
foreach (var item in stringList)
{
resultt += item + ", ";
}
resultt = resultt.TrimEnd(',',' ');
Console.WriteLine(resultt);
If you are concatenating a lot of strings using StringBuilder will be more efficient.
Upvotes: 2