Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I check if a List contains an object of a certain type? C#

Tags:

I have a list (called Within), and it contains objects of type GameObject. GameObject is a parent class to many others, including Dog and Ball. I want to make a method that returns true if Within contains any object of type Ball, but I don't know how to do this.

I've tried using Count<>, Any<>, Find<> and a few other methods provided within C#, but I couldn't get them to work.

public bool DetectBall(List<GameObject> Within) {     //if Within contains any object of type ball:     {         return true;     } } 
like image 961
Kiloku Avatar asked Nov 21 '11 18:11

Kiloku


People also ask

How do you check if an object is of a certain type C#?

To determine whether an object is a specific type, you can use your language's type comparison keyword or construct. For example, you can use the TypeOf… Is construct in Visual Basic or the is keyword in C#. The GetType method is inherited by all types that derive from Object.

How do you check if an object is a certain type of object?

You can check object type in Java by using the instanceof keyword. Determining object type is important if you're processing a collection such as an array that contains more than one type of object. For example, you might have an array with string and integer representations of numbers.

How do you check if a list of object contains a value?

You can use the Enumerable. Where extension method: var matches = myList.


1 Answers

if (within.OfType<Ball>().Any()) 

The generic parameter of all LINQ methods except Cast<T>() and OfType<T>() is used to allow the method call to compile and must be compatible with the type of the list (or for a covariant cast). They cannot be used to filter by type.

like image 86
SLaks Avatar answered Sep 19 '22 07:09

SLaks