Retrieving Property name from lambda expression

前端 未结 21 2049
迷失自我
迷失自我 2020-11-21 11:12

Is there a better way to get the Property name when passed in via a lambda expression? Here is what i currently have.

eg.

GetSortingInfo         


        
21条回答
  •  Happy的楠姐
    2020-11-21 12:03

    I leave this function if you want to get multiples fields:

    /// 
        /// Get properties separated by , (Ex: to invoke 'd => new { d.FirstName, d.LastName }')
        /// 
        /// 
        /// 
        /// 
        public static string GetFields(Expression> exp)
        {
            MemberExpression body = exp.Body as MemberExpression;
            var fields = new List();
            if (body == null)
            {
                NewExpression ubody = exp.Body as NewExpression;
                if (ubody != null)
                    foreach (var arg in ubody.Arguments)
                    {
                        fields.Add((arg as MemberExpression).Member.Name);
                    }
            }
    
            return string.Join(",", fields);
        }
    

提交回复
热议问题