我可以使用LINQ从List <string> </string> </person>返回List <person>

时间:2010-10-30 00:26:09

标签: c# linq linq-to-objects

我可以使用LINQ从List<Person>返回List<String>,如下所示:

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

提前致谢。

2 个答案:

答案 0 :(得分:9)

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

这将返回IEnumerable<Person>。如果你想要一个清单:

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

答案 1 :(得分:1)

这也有效:

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

然后你必须这样做:

var personsList = persons.ToList();

将LINQ表达式实现List<Person>实例中。