我需要将公共属性(即具有同名的属性)从两个不同类的对象转换为数组。但是我无法在Join
附近提供正确的语法。这是我的代码。请帮忙
PropertyInfo[] objAllProps = SourceInstance.GetType().GetProperties();
PropertyInfo[] objAllProps_Target = TargetInstance.GetType().GetProperties();
PropertyInfo[] CommonProperties =
from allprops in objAllProps join
allprop_target in objAllProps_Target on
allprops.Name.Equals(allprop_target)
select new PropertyInfo[] {
allprop_target,
}
.ToArray<PropertyInfo>();
答案 0 :(得分:4)
我建议使用不同的集合类型HashSet<string>
而不是PropertyInfo[]
:
HashSet<string> NamesToFind = new HashSet<string>(SourceInstance
.GetType()
.GetProperties()
.Select(property => property.Name));
// Common properties: properties of TargetInstance such that
// there's a property of SourceInstance with the same name
PropertyInfo[] CommonProperties = TargetInstance
.GetType()
.GetProperties()
.Where(property => NamesToFind.Contains(property.Name))
.ToArray();