Possible Duplicate:
Lambda Expression: == vs. .Equals()

Hi,

I use a lot the keyword Equals to compare variables and other stuff.

but

wines = wines.Where(d => d.Region.Equals(paramRegion)).ToList();

return an error at runtime when in the data Region is NULL

I had to use the code

wines = wines.Where(d => d.Region == paramRegion).ToList();

to get rid of the error.

Any ideas why this raises an error?

Thanks.

有帮助吗?

解决方案

You cannot call instance methods with null object reference. You should check that the Region is not null before calling its instance methods.

wines = wines.Where(d => d.Region != null && d.Region.Equals(paramRegion)).ToList();

The d.Region == paramRegion is (most likely) expanded to object.Equals(d.Region, paramRegion) and that static method does check whether the parameters are null or not before calling the Equals() method.

You can also write the condition in different order if you know that the paramRegion cannot be null.

Debug.Assert(paramRegion != null);
wines = wines.Where(d => paramRegion.Equals(d.Region)).ToList();

其他提示

Basically if

d.Region == null

then any method call, here it's Equals(...) on that will raise an exception since it's not initialized.

Use can use:

paramRegion.Equals(d.Region)
许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top