简体   繁体   English

c# list select 意外(对我而言)行为

[英]c# list select unexpected (for me) behaviour

1. var test = new List<foo>() { new foo { prop1 ="1prop1", prop2 = "1prop2" }, new foo { prop1 = "2prop1", prop2 = "2prop2" }  };

2. var test2 = test.Select(x => x.prop1 = "changed");

3. var test3 = test2.First();

Please, explain this behaviour to me.请向我解释这种行为。
Why foo.prop1 values change after line 3?为什么 foo.prop1 值在第 3 行之后发生变化?

This is to do with deferred execution.这与延迟执行有关。 Most linq methods defer execution until the resulting enumerable is actually enumerated.大多数 linq 方法推迟执行,直到实际枚举结果可枚举。 So when you run the Select statement it just creates an Enumerable that is ready to run the appropriate selector.因此,当您运行SELECT语句时,它只需创建可枚举即可运行相应的选择器。

When you call First on the enumerable it runs the transform on the first item, thus changing its value.当您在可枚举项上调用First时,它会在第一项上运行转换,从而更改其值。

This all assumes that you intended to write x.prop1 = "changed" and not x.prop1 == "changed" .这一切都假设您打算编写x.prop1 = "changed"而不是x.prop1 == "changed" The former is the assignment operator which sets the value of x.prop1 and returns the set value.前者是赋值运算符,它设置x.prop1的值并返回设置的值。 The latter is the equality operator and will return a boolean based on whether they are equal or not.后者是相等运算符,将根据它们是否相等返回一个布尔值。

= is assignment, which means it actually changes values. =是赋值,这意味着它实际上改变了值。

You want to use == instead, to check for equality.您想改用==检查相等性。

Try:尝试:

var test2 = test.Select(x => x.prop1 == "changed"); var test2 = test.Select(x => x.prop1 == "changed");

当您可能想要进行相等比较==时,您正在进行分配=

 var test2 = test.Select(x => x.prop1 == "changed");

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM