Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Join List<string> Together with Commas Plus "and" for Last Element

Tags:

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.

like image 337
Gabriel Nahmias Avatar asked Jul 09 '13 23:07

Gabriel Nahmias


People also ask

How do you join a list of strings in Python?

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() .

How do I create a comma separated string from a list of strings in C#?

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.

Which operation you will use to join two strings?

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.


2 Answers

You could do this

string finalString = String.Join(", ", myList.ToArray(), 0, myList.Count - 1) + ", and " + myList.LastOrDefault(); 
like image 195
keyboardP Avatar answered Oct 29 '22 15:10

keyboardP


Here is a solution which works with empty lists and list with a single item in them:

C#

return list.Count() > 1 ? string.Join(", ", list.Take(list.Count() - 1)) + " and " + list.Last() : list.FirstOrDefault(); 

VB

Return If(list.Count() > 1, String.Join(", ", list.Take(list.Count() - 1)) + " and " + list.Last(), list.FirstOrDefault()) 
like image 37
Darren Avatar answered Oct 29 '22 15:10

Darren