How to get list of class properties into string using LINQ?

744 views Asked by At

I have a following class:

public class Person
    {
        public string FirstName = string.Empty;
        public string LastName = string.Empty;
    }

and list of that class:

List<Person> listOfPeople = new List<Person>();

How do I get list FirstNames into string or string list variable from listOfPeople without using foreach and looping through it? I want to get something like:

string firstNames= "Bob, Jack, Bill";
2

There are 2 answers

0
juharr On BEST ANSWER

A simple Select combined with string.Join will give you what you want.

string firstNames = string.Join(", ", listOfPeople.Select(p=>p.FirstName));

Depending on what version of .Net you are using you might also need to add a ToArray after the Select as the overload of string.Join that takes a IEnumerable<string> was not added until .Net 4.

On a side note consider turning your public fields into properties.

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

    public Person()
    {
        FirstName = string.Empty;
        LastName = string.Empty;
    }
}
1
Suresh Kumar Veluswamy On

You can use linq Aggregate function to achieve this

listOfPeople.Select(person => person.FirstName).Aggregate((i, j) => i + ", " + j);