我正在使用linq查询来获取从某些指定类派生的所有类的所有属性的名称,如下所示:
/// <summary>
/// Gets all visible properties of classes deriving from the specified base type
/// </summary>
private HashSet<string> GetDerivedPropertyNames(Type baseType)
{
// get all property names of the properties of types that derive from the base type
var propertyNames =
from type in baseType.Assembly.GetTypes()
where type.IsSubclassOf(baseType)
select Array.ConvertAll(type.GetProperties(), property => property.Name);
// the hashset constructor will filter out all duplicate property names
return new HashSet<string>(propertyNames);
}
但是这不能编译,因为linq查询的结果是IEnumerable<string[]>
,而我想要IEnumerable<string>
。如何将结果展平为单个IEnumerable<string>
?
答案 0 :(得分:2)
我认为你想要SelectMany
:
var propertyNames = baseType.Assembly.GetTypes()
.Where(type => type.IsSubclassOf(baseType))
.SelectMany(type => type.GetProperties().Select(property => property.Name));
可能一次包括“明显”步骤:
var propertyNames = baseType.Assembly.GetTypes()
.Where(type => type.IsSubclassOf(baseType))
.SelectMany(type => type.GetProperties().Select(property => property.Name))
.Distinct();