我很难理解这个Linq查询做得是否正确。不幸的是,我是个新手,在使用lambda表达式时仍然有很多问题。
m_ItemList
包含不同GameObject
:的列表
Fruit
对象bool Value;
Cars
对象bool Bought;
- 其他
这些对象有不同的脚本行为,我只想隔离那些拥有脚本Cars
的对象,并检索true
上拥有bool
var的对象。这是我首先创建的查询。
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的答案非常相似,实际上非常接近您最初仅使用Where
和TryGetComponent
的尝试
itemBought = m_ItemList.Where(item => item.TryGetComponent<Cars>(out var car) && car.Bought).ToList();
TryGetComponent
已经包含空检查,因为如果在对象上找不到组件,它已经返回false
。