我有以下课程:
class Person
{
public string Name { get; set; }
}
class Student
{
public string Name { get; set; }
}
我有一份人员名单:
IList<Person> persons = new List<Person>
{
new Person() { Name = "Bill" },
new Person() { Name = "Bob" },
new Person() { Name = "Henry" },
};
我在foreach
循环中将项目添加到新集合中:
IList<Student> students = new List<Student>();
//Is it possible to nest the following rows in linq method?
foreach (var person in persons)
{
students.Add(new Student() { Name = person.Name });
}
是否可以嵌套foreach
并将项目添加到linq
方法?
答案 0 :(得分:3)
如果你的意思是用LINQ查询替换foreach
循环(不太确定你为什么要在你的问题中讨论嵌套循环),那么你可以试试这个:
IList<Student> students = persons.Select(p => new Student { Name = p.Name }).ToList();
或者如果您愿意:
IList<Student> students = (from p in persons select new Student { Name = p.Name }).ToList();