[英]weird result when using linq to set value
我試圖使用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();
通常,不生成產生副作用的LINQ查詢總是一個好主意。 這里的整個目標是在Select()
語句中產生副作用。
ToList()
導致它生效的原因是LINQ查詢在枚舉結果之前不會執行。 ToList()
導致查詢結果被完全枚舉(以便構建列表)。 如果你要寫:
foreach (Person person in people.Select(x => { x.name = "c"; return x; }))
{
當foreach遍歷結果時,您會看到效果發生。
話雖如此,使用LINQ寫入值的“正確”方法是過濾,然后稍后更改:
var peopleToEdit = people.Where(p => string.IsNullOrWhiteSpace(p.Name));
foreach(var person in peopleToEdit)
person.Name = "Foo"; // Assign like so
基本上,查詢應該是無副作用的,然后使用常規控制流來實際編輯值。
使用.Where子句。
List<Person> people = new List<Person>() { new Person("C"), new Person("b") };
var something = people.Where(x => x.name == "C");
foreach(var x in something)
{
}
這是經過測試的
people.Where(p => string.IsNullOrWhiteSpace(p.Name)).ToList().ForEach(cc=>cc.Name="Foo");
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.