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.