tags:

views:

74

answers:

1

Linq has this handy function Where that lets me filter the results of an enumerable...

foreach (var method in typeof(Program).GetMethods())
{
    foreach (var attr in method.GetCustomAttributes(inherit: true).Where(a => a is UrlAttribute))
    {
        Console.WriteLine(((UrlAttribute)attr).Url);
    }
}

But it doesn't seem very handy for retrieving only objects of a certain type, because I still have to cast them. Linq doesn't have a method to solve this problem, does it?


Is this a good solution?

public static class Extensions
{
    public static IEnumerable<T> OfType<T>(this IEnumerable<object> e)
    {
        return e.Where(x => x is T).Cast<T>();
    }
}

I'm learning how to write my own attributes, and I'm trying to figure out how to retrieve them all now.

+7  A: 

I'm pretty sure that method already exists.

http://msdn.microsoft.com/en-us/library/bb360913.aspx

Am I missing something in your question?

Joshua Evensen
Hahaha... I was looking for such a method in the intellisense popup, but couldn't think of what it would be called, so I assumed it didn't exist. Then I started writing my own method, and figured "OfType" would be a good name for it.... go figures.
Mark