如何在Linq中实现无空值查询



我很难理解这个Linq查询做得是否正确。不幸的是,我是个新手,在使用lambda表达式时仍然有很多问题。

m_ItemList包含不同GameObject:的列表

  • Fruit对象
    • bool Value;
  • Cars对象
    • bool Bought;
  • 其他

这些对象有不同的脚本行为,我只想隔离那些拥有脚本Cars的对象,并检索true上拥有boolvar的对象。这是我首先创建的查询。

itemBought = m_ItemList.Where(x => x.GetComponent<Cars>().Bought).ToList();

显然,这给了我一个Exception的问题,因为并不是每个人都附带了Cars脚本组件。

因此,我找到了解决方案:

itemBought = m_ItemList.Where(x => x.GetComponent<Cars>()).Where(x => x.GetComponent<Cars>().Bought).ToList();

这很好,但很糟糕,我甚至不确定这是实现它的最佳方式(可能在表演中也很糟糕(。

有什么帮助吗?

GetComponent是一个相对昂贵的操作,所以我会尝试每个对象只调用一次。因此,在GetComponent的结果中进行选择,过滤掉Bought值为假的null和非null:

itemBought = m_ItemList.Select(x => x.GetComponent<Cars>())
.Where(c => c != null && c.Bought == true)
.ToList();

如果您可以制作List<Cars>List<MonoBehaviour>类型的itemBought或其他类似的东西,并且避免了在以后的行中使用GetComponent<Cars>,则此操作有效

与Ruzihm的答案非常相似,实际上非常接近您最初仅使用WhereTryGetComponent的尝试

itemBought = m_ItemList.Where(item => item.TryGetComponent<Cars>(out var car) && car.Bought).ToList();

TryGetComponent已经包含空检查,因为如果在对象上找不到组件,它已经返回false

最新更新