c# - 使用c#获取两个不同对象的公共(public)属性

标签 c# .net linq

我需要从两个不同类的对象中获取公共(public)属性(即具有相同名称的.properties)到一个数组中。但我无法在 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>();

最佳答案

我建议使用不同 集合类型 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();

关于c# - 使用c#获取两个不同对象的公共(public)属性,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44364909/

相关文章:

c# - 删除动态控件 : Clear is working but not remove

c# - XPath 查询中的撇号 (')

c# - 无法转换类型为 'System.Data.Objects.ObjectQuery` 的对象 1 [Manager.Data.Channel ]' to type ' Manager.Data.Channel'

c# - 关于处理 DataContext 和 DataBind()

c# - 编码 UI - Keyboard.sendkeys - 包含特殊字符的文件的发送路径

asp.net - User.IsInRole 返回 false

.net - .NET 可达到的最大内存?

c# - 如何从 Azure 函数返回 AcceptedAtRouteResult?

c# - 产量返回 brainfreeze

c# - 在 PartialViewResult() 方法中重定向页面