简化循环以获取类的属性

J. *_*Doe 3 c# linq

我有两个foreach循环来获取我的一个类的所有线性属性.

foreach (PropertyInfo property in GetType().GetProperties())
{
  foreach (Attribute attribute in property.GetCustomAttributes(true))
  {
  }
}
Run Code Online (Sandbox Code Playgroud)

如何将这两个循环简化为一个循环或linq操作以获取类属性?

its*_*e86 6

你可以信赖 SelectMany()

var attributes = GetType().GetProperties()
                     .SelectMany(p => p.GetCustomAttributes(true));

foreach (var attribute in attributes)
{
    // Code goes here
}
Run Code Online (Sandbox Code Playgroud)