LINQ: List Classes implementing the IEnumerable Interface

A DevCurry.com reader ‘Richard’ mailed me with a question. He wanted to know an easy way to find all the types that implement the IEnumerable interface, or for that matter, any interface. Here’s a piece of LINQ code that lists all the types implementing the IEnumerable interface

public static void Main(string[] args) 
{ 
   var t = typeof(IEnumerable); 

   var typesIEnum = AppDomain.CurrentDomain
  .GetAssemblies()
  .SelectMany(x => x.GetTypes())
  .Where(x => t.IsAssignableFrom(x)); 

foreach (var types in typesIEnum) 
{
 Console.WriteLine(types.FullName); 
}
Console.ReadLine(); 
}

Here’s a partial output

types implementing interface

Note: The results may not be the same on your machine. Note that we are referring to the GetExportedTypes() which returns type visible outside the assembly. So if you have added new references (assemblies) to your project which implements the IEnumerable or changed the access modifiers of your custom types, you will get different results.

Liked this tip? Read some more LINQ Tips

No comments:

Post a Comment