How to determine if a collection contains an instance of a particular type?

Suppose I create a collection like

Collection<IMyType> coll; 

Then I have many IMyTypem implementations like, T1, T2, T3 ...

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

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

here the parameter should be a class, not an instance of the class. How to write code for this kind of problem?

+7
collections c #
source share
1 answer

You can do:

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

And then call it like this:

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

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

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

This is different, though, since it will return true if the command also contains any subclasses of T1.

+9
source share

All Articles