Skip to content

Instantly share code, notes, and snippets.

@Gabboxl
Created September 6, 2023 21:23
Show Gist options
  • Save Gabboxl/0470bb60b11942a13b0d063c115a6771 to your computer and use it in GitHub Desktop.
Save Gabboxl/0470bb60b11942a13b0d063c115a6771 to your computer and use it in GitHub Desktop.
select aggreate join strings c#

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.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment