views:

62

answers:

2

Can I using LINQ return a List<Person> from a List<String> like the following:

// this is not valid code, just to explain the idea
var persons = new string[] {"Tom", "Adam"}.ToList<Person>(str => Name = str);

Thanks in advance.

+7  A: 
var people = new string[] {"Tom", "Adam"}
    .Select(str => new Person {Name = str});

This will return an IEnumerable<Person>. If you'd like a list:

var people = new string[] {"Tom", "Adam"}
    .Select(str => new Person {Name = str})
    .ToList();
Yuriy Faktorovich
A: 

This works too:

var names = new []{"Tom", "Adam"};
var persons = from name in names
              select new Person {Name = name};

and then you will have to do:

var personsList = persons.ToList();

in order to materialize the LINQ expression into a List<Person> instance.

Peter Lillevold