我试图使用 LINQ 在我的列表中设置一些值,但不知何故,以下代码将没有设置值。
class Person
{
public string name;
public Person(string name)
{
this.name = name;
}
}
List<Person> people = new List<Person>() { new Person("a"), new Person("b") };
people.Select(x => { x.name = "c"; return x; });
foreach (Person person in people)
{
Console.WriteLine(person.name);
}
但是,如果我在调用 select 方法后添加 ToList() ,则会设置值:
List<Person> people = new List<Person>() { new Person("a"), new Person("b") };
people.Select(x => { x.name = "c"; return x; }).ToList();
更奇怪的是,如果我在单独的行上调用 ToList() ,它也不起作用:
List<Person> people = new List<Person>() { new Person("a"), new Person("b") };
people.Select(x => { x.name = "c"; return x; });
people.ToList();