Concatenate string properties of objects through Linq?

  • Thread starter Thread starter csharper
  • Start date Start date
C

csharper

Suppose I have a Student class:

public class Student{
public string FirstName { get; set; }
public string LastName { get; set; }
}

And I have a List<Student> students collection.

Now, I'd like to save all students to a text file as FistName + " " + LastName delimited by a comma(,). In other words, the input is this List<Student> students collection, and the output should be something like below:

Aaron Brown, Chris Davidson, Ellen Feliciano, Gary Hutchinson, Ian Jenkins

I know this is very very easy to do using C#. What I am looking for is a single liner LINQ /Lamda expression to achieve this. String.Join(string, string[]) probably won't work since the input is not a string array.

Any idea? Thanks.
 
And here is the answer:

string myStudents = String.Join(", ", students.Select(s => s.FirstName + " " + s.LastName));
 
And here is the answer:

string myStudents = String.Join(", ", students.Select(s => s.FirstName + " " + s.LastName));

There are other ways.

Example:

string myStudents = students.Aggregate("", (tot, nxt) => tot + "," +
nxt.FirstName + " " + nxt.LastName).Substring(1);

But I would probably do it like you did.

Arne
 
Back
Top