简体   繁体   中英

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?

This is to do with deferred execution. Most linq methods defer execution until the resulting enumerable is actually enumerated. So when you run the Select statement it just creates an Enumerable that is ready to run the appropriate selector.

When you call First on the enumerable it runs the transform on the first item, thus changing its value.

This all assumes that you intended to write x.prop1 = "changed" and not x.prop1 == "changed" . The former is the assignment operator which sets the value of x.prop1 and returns the set value. 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");

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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