Álvaro García
Álvaro García

Reputation: 19396

Is there a way to create a list of property values from a list of some type?

Imagine that I have this class:

class Person
{
    string Name { get; set; }
    string Surname { get; set; }
    string Other { get; set; }
}

I have a IList<Person> and now I want an IList<string> that is a sequence of the Name of each person.

I can use this loop:

var Names = new List<string>();
foreach (Person p in Persons)
{
    Names.Add(p.Name);
}

But, I would like to know if linq (or any other option) allows me to do it more easily?

Thanks.

Upvotes: 3

Views: 61

Answers (3)

Jodrell
Jodrell

Reputation: 35746

like this?

var Names = Persons.Select(p => p.Name).ToList();

Upvotes: 3

RoughPlace
RoughPlace

Reputation: 1121

var items = new List<Person>();
items.Add(...);
items.Add(...);


var people = items.Select(x=>x.name);

Upvotes: 1

Yaugen Vlasau
Yaugen Vlasau

Reputation: 2218

lstPersons.Select(x=> x.Name).ToList()

Upvotes: 3

Related Questions