C#/ Linq:哪里X是Y?

时间:2010-08-09 01:25:14

标签: c# linq

Linq有这个方便的功能Where,让我可以过滤可枚举的结果......

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);
    }
}

但是对于仅检索某种类型的对象似乎并不是很方便,因为我仍然需要强制转换它们。 Linq没有解决这个问题的方法,是吗?


这是一个很好的解决方案吗?

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

我正在学习如何编写自己的属性,而我正试图弄清楚如何全部检索它们。

1 个答案:

答案 0 :(得分:7)

我很确定该方法已经存在。

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

我在你的问题中遗漏了什么?