Linq Lambda expression == and Equals operator

var list = new List<string>();
var word = "some word";
list.Add("some word");
list.Add("some sentence");
list.Add(word);

I know Equals compare the value stored in the reference while "==" compares whether two references point to the same object. But is it the same even in lambda expressions?

list.RemoveAll(x => x.Equals("some word"));
list.RemoveAll(x => x == "some word");

Do these statements produces same result?

Jon Skeet
people
quotationmark

I know Equals compare the value stored in the reference while "==" compares whether two references point to the same object.

No, that's just the behaviour of the default == operator for reference types. When both sides of == have a compile-time type of string, the bool operator==(string, string) overload declared in the string class is used, and you get the same result as Equals, when the target of the call isn't null.

That behaviour is exactly the same in regular code as in lambda expressions. Code written in a lambda expression should behave exactly the same way as code written not in a lambda expression... although if the lambda expression is converted to an expression tree, the compiler only emits the code as data, so it's up to whatever's consuming the expression tree to do the right thing with it.

So yes, the code should work absolutely fine - the only difference between using Equals and using == is that if you list contains any null elements, the x.Equals(...) call will throw a NullReferenceException. Personally I usually compare strings with == just for simplicity.

people

See more on this question at Stackoverflow