C#/林克 : Where X is Y?

标签 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>();
    }
}

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

最佳答案

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

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

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

关于C#/林克 : Where X is Y?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3436820/

相关文章:

c# - 尝试用递归更优雅地解决电话词

c# - OData中解压gzip

c# - 多对多表上的 LEFT LINQ TO SQL C# JOIN

c# - 使用 Workflow 的 ASP.net 页面导航

c# - 向 Unity 注册 IAuthenticationManager

c# - 条件运算符 (? :) without return value

c# - StackOverflowException 试图通过 WCF 服务将 Linq 查询结果作为列表返回

c# - Linq - 使用 GroupBy 我自己的类型与匿名类型

c# 如何以编程方式禁用 Windows 8 特定功能

c# - datagridview 不允许用户删除行