我可以使用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);
提前致谢。
答案 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>
实例中。