Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to detect if collection contain instance of specific type?

Tags:

c#

collections

Suppose I create collection like

Collection<IMyType> coll;

Then I have many implelentations of IMyTypem like, T1, T2, T3...

Then I want know if the collection coll contains a instance of type T1. So I want to write a method like

public bool ContainType( <T>){...}

here the param should be class type, not class instance. How to write code for this kind of issue?

like image 689
KentZhou Avatar asked Mar 22 '10 19:03

KentZhou


People also ask

How do you check if an object is a specific type?

To determine whether an object is a specific type, you can use your language's type comparison keyword or construct.

Which method can be used to check a particular value exists in the collection?

The contains() method is used to check if a particular value exists.

How do you check if an collection is contains a value JAVA?

The Collection. contains() method check if a collection contains a given object, using the . equals() method to perform the comparison. Returns true if this collection contains the specified element.

How do I find the instance of a class in C#?

This method returns the instances of the Type class that are used for consideration. Syntax: public Type GetType (); Return Value: This method return the exact runtime type of the current instance.


1 Answers

You can do:

 public bool ContainsType(this IEnumerable collection, Type type)
 {
      return collection.Any(i => i.GetType() == type);
 }

And then call it like:

 bool hasType = coll.ContainsType(typeof(T1));

If you want to see if a collection contains a type that is convertible to the specified type, you can do:

bool hasType = coll.OfType<T1>().Any();

This is different, though, as it will return true if coll contains any subclasses of T1 as well.

like image 70
Reed Copsey Avatar answered Sep 30 '22 17:09

Reed Copsey