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>();
}
}
我正在学习如何编写我自己的属性,现在我正在尝试弄清楚如何检索它们。
最佳答案
关于C#/林克 : Where X is Y?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3436820/