Click here to Skip to main content
15,911,142 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
I need to separate a list of returned names by comma in my MVC project View. I'm struggling to achieve and i have a feeling its an easy job.

C#
var names  = dbcontext.EmployeeTable.Select(x => x.Name).ToList();


in my view i'm looping through this object like this:

C#
@foreach(e in names)
{
   //i need to separate the names by a comma i.e
   // john, jen, glen 

}


could some please help?

Thank you

What I have tried:

I have tried to use string.join(","name) but for some reason this is not working
Posted
Updated 13-Dec-17 3:48am
v2

The simplest option would be string.Join[^]:
C#
string nameList = string.Join(", ", names);
 
Share this answer
 
Comments
________________ 14-Dec-17 1:39am    
This is the best solution.
I did elapsed ticks test for all 3 answers 10000 repetitions:

string.Join -> 870894
names.Aggregate -> 19875057
AllNamesSeparatedByComma -> 1528247
As variant:

public string AllNamesSeparatedByComma(List<string> names)
		{
			
			StringBuilder allNames = new StringBuilder();

			foreach(string e in names)
			{
				allNames.AppendFormat("{0},", e);
			}

			return allNames.ToString();
		}
 
Share this answer
 
Use Aggregate

string nameList = names.Aggregate((a, b) => a + ", " + b);
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900