You can use the Select
and Aggregate
LINQ methods to create a comma-separated string of all teacher names. Here's how you can do it:
List<Teacher> teachers = new List<Teacher>
{
new Teacher { teacherId = "1", teacherName = "Teacher1" },
new Teacher { teacherId = "2", teacherName = "Teacher2" },
// ... other teachers ...
};
string result = teachers.Select(t => t.teacherName)
.Aggregate((current, next) => current + ", " + next);
This code first uses the Select
method to transform the list of Teacher
objects into a list of their names, and then it uses the Aggregate
method to join all the names into a single string, separated by commas.
However, for the purpose of joining strings with a separator, .NET provides a more straightforward method: String.Join
. Here's the equivalent code using String.Join
:
string result = String.Join(", ", teachers.Select(t => t.teacherName));
This version is likely to be faster and more efficient, especially for large lists, because it avoids creating a lot of temporary strings.