I know I could figure a way out but I am wondering if there is a more concise solution. There's always String.Join(", ", lList)
and lList.Aggregate((a, b) => a + ", " + b);
but I want to add an exception for the last one to have ", and "
as its joining string. Does Aggregate()
have some index value somewhere I can use? Thanks.
If you want to concatenate a list of numbers ( int or float ) into a single string, apply the str() function to each element in the list comprehension to convert numbers to strings, then concatenate them with join() .
The standard solution to convert a List<string> to a comma-separated string in C# is using the string. Join() method. It concatenates members of the specified collection using the specified delimiter between each item.
You concatenate strings by using the + operator. For string literals and string constants, concatenation occurs at compile time; no run-time concatenation occurs. For string variables, concatenation occurs only at run time.
You could do this
string finalString = String.Join(", ", myList.ToArray(), 0, myList.Count - 1) + ", and " + myList.LastOrDefault();
Here is a solution which works with empty lists and list with a single item in them:
return list.Count() > 1 ? string.Join(", ", list.Take(list.Count() - 1)) + " and " + list.Last() : list.FirstOrDefault();
Return If(list.Count() > 1, String.Join(", ", list.Take(list.Count() - 1)) + " and " + list.Last(), list.FirstOrDefault())
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