C# Cast list using Linq using Where function -
i'm trying optimize part of function gets objects within unity contains component.
current code looks this
collider[] collisions = physics.overlapsphere(point, range); foreach (collider item in collisions) { if (item.getcomponent<rigidbody2d>()) { rigidbodies.add(item.getcomponent<rigidbody2d>()); } }
first list of objects colliders, run thought foreach loop ones contains rigidbody2d component
i'm trying turn single line of code using linq. i'm trying along line
collider[] collisions = physics.overlapsphere(point, range); rigidbodies = (list<rigidbody2d>)collisions.tolist().oftype<rigidbody2d>().where(x => x.getcomponent<rigidbody2d>() == true);
unfortunately throws invalidcastexception
you need add call tolist()
on method chain.
you'll able rid of cast altogether:
rigidbodies = collisions .oftype<rigidbody2d>() .where(x => x.getcomponent<rigidbody2d>()) .tolist();