当 Lambda 查询使用“Contains”时并且它不符合条件“对象引用未设置到对象的实例”错误返回

发布于 2024-10-07 09:02:27 字数 641 浏览 0 评论 0原文

平台 C#,Dot net 4.0

var city0 = DataCache.GetAllCities().Where(c => c.GeoName.Contains("Dubai")).FirstOrDefault();

变量 Duabi 存在于数据中,返回城市对象

var city1 = DataCache.GetAllCities().Where(c => c.CityID== 23804982) .FirstOrDefault();

id 23804982 不存在于数据中,返回 null 对象

var city2 = DataCache.GetAllCities().Where(c => c.GeoName.Contains("WrongCityName")).FirstOrDefault();

变量 WrongCityName 不存在于数据中,这会返回以下错误。

未将对象引用设置为对象的实例。

[编辑] 我在执行最后一个查询时收到错误。当我评估 city2 时不是

Platform C#, Dot net 4.0

var city0 = DataCache.GetAllCities().Where(c => c.GeoName.Contains("Dubai")).FirstOrDefault();

The Variable Duabi exists in data and this returns city object

var city1 = DataCache.GetAllCities().Where(c => c.CityID== 23804982) .FirstOrDefault();

The id 23804982 is not exists in data and this returns null object

var city2 = DataCache.GetAllCities().Where(c => c.GeoName.Contains("WrongCityName")).FirstOrDefault();

The Variable WrongCityName does not exists in data and this returns the following error.

Object reference not set to an instance of an object.

[EDIT]
I got the error when the last query executed. Not when I evaluate city2

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

绾颜 2024-10-14 09:02:27

好吧,city2 将为 null,因为您使用了 FirstOrDefault - 并且类的默认值为 null。

您应该在使用它之前检查它是否为空:

if (city2 != null)
{
    // Okay, I found a matching city. Now I can use it
}

现在假设您实际给出的代码正在执行而没有任何问题。如果 c.GeoName 对于某些城市为 null,则不会...因为您将在 null 引用上调用 Contains。您可以通过以下方式修复该问题:

var city2 = DataCache.GetAllCities()
                     .Where(c => c.GeoName != null &&
                                 c.GeoName.Contains("WrongCityName"))
                     .FirstOrDefault();

Well, city2 will be null, because you've used FirstOrDefault - and the default value for classes is null.

You should check it for nullity before using it:

if (city2 != null)
{
    // Okay, I found a matching city. Now I can use it
}

Now that's assuming the code you've actually given is executing without any problems. It wouldn't if c.GeoName was null for some city... because you'd be calling Contains on a null reference. You can fix that with:

var city2 = DataCache.GetAllCities()
                     .Where(c => c.GeoName != null &&
                                 c.GeoName.Contains("WrongCityName"))
                     .FirstOrDefault();
溺深海 2024-10-14 09:02:27

也许cc.GeoName 为空——您检查过这些吗?

Maybe c or c.GeoName is null -- have you checked those?

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文