2013-12-21 76 views
2

假設我有此對象PARAMS到lambda表達式

class SomeObject 
    { 
     public int id { get; set; } 
     public string name {get;set;} 
     public string description {get;set;} 
     public anotherObject obj {get;set;} 
    } 

和此擴展方法,如果該屬性的名稱作爲參數nameis發送其去除從列表中一個的PropertyInfo

public static IList<PropertyInfo> Except(this IList<PropertyInfo> Properties, params string[] PropertiesToExecludeNames) 
     { 
      return Properties.Where(p => !(PropertiesToExecludeNames ?? Enumerable.Empty<String>()).Any(s => s == p.Name)).ToList(); 
     } 

和我用它如下

var someObject = new SomeObject(); 
var Properties = someObject.GetType().GetProperties(); 
Properties = Properties.Except("name","obj"); 

這是不壞,但我想找到一種方法來避免發送作爲字符串的屬性名稱,有沒有辦法讓這個函數使用lambda表達式,以便我可以在Visual Studio中寫入屬性到Except的建議?

更新:根據所選擇的答案下面也支持UnaryExpressions

public static IEnumerable<PropertyInfo> GetPropertyInfosExcept<T>(this T obj, params Expression<Func<T, object>>[] lambda) 
      { 
       HashSet<string> set = new HashSet<string>(
         lambda.Select(l => l.GetMemberInfo() as PropertyInfo) 
           .Select(x => x.Name)); 
       return typeof(T).GetProperties().Where(p => !set.Contains(p.Name)); 
      } 


public static MemberInfo GetMemberInfo(this LambdaExpression expression) 
      { 
       return expression.Body is MemberExpression ? ((MemberExpression)expression.Body).Member : ((MemberExpression)(((UnaryExpression)expression.Body).Operand)).Member; 
      } 

回答

3
var pInfos = new SomeObject().GetPropertyInfosExcept(x => x.obj, x => x.name) 
      .ToList(); 

public static IEnumerable<PropertyInfo> GetPropertyInfosExcept<T>(
          this T obj, params Expression<Func<T, object>>[] lambda) 
{ 
    HashSet<string> set = new HashSet<string>(
      lambda.Select(l => (l.Body as MemberExpression).Member as PropertyInfo) 
        .Select(x=>x.Name) 
     ); 

    return typeof(T).GetProperties().Where(p => !set.Contains(p.Name)); 
}