Concatenate string properties of objects through Linq?

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.
 
C

csharper

And here is the answer:

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

Arne Vajhøj

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
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Top