开发者

C#/Linq: Where X is Y?

Linq has this handy function Where that lets me filter th开发者_如何学编程e 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.


I'm pretty sure that method already exists.

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

Am I missing something in your question?

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜