2
5

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

ラムダ式でプロパティ名を取得する

Posted at

Expression<Func<TEntity, object>> expressionを使う。
プロパティ名を取得できれば、ASP .NET MVC のHTMLヘルパ作りなどが捗る。

Expressionの使い方は、詳しい資料を別途参考にしてください。

ExpressionExtentions.cs
    public static class ExpressionExtentions
    {
        /// <summary>
        /// MemberExpressionへの変換(string以外の型に対応するため)
        /// </summary>
        /// <param name="expression"></param>
        /// <returns></returns>
        public static MemberExpression ToMemberExpression(LambdaExpression expression)
        {
            var memberExpression = expression.Body as MemberExpression;
            if (memberExpression != null) return memberExpression;
            var unaryExpression = expression.Body as UnaryExpression;
            if (unaryExpression != null) return unaryExpression.Operand as MemberExpression;
            return memberExpression;
        }


        /// <summary>
        /// プロパティ名を取得する
        /// </summary>
        /// <param name="expression"></param>
        /// <param name="names"></param>
        /// <returns></returns>
        public static IEnumerable<string> GetPropertyNames(this LambdaExpression expression)
        {
            return GetPropertyNames(ToMemberExpression(expression));
        }

        /// <summary>
        /// プロパティ名を取得する(再帰で取得)
        /// </summary>
        /// <param name="memberExpression"></param>
        /// <param name="names"></param>
        /// <returns></returns>
        public static IEnumerable<string> GetPropertyNames(MemberExpression memberExpression, IList<string> names = null)
        {
            if (names == null)
            {
                names = new List<string>();
            }
            if (memberExpression.Expression is MemberExpression)
            {
                GetPropertyNames(memberExpression.Expression as MemberExpression, names);
            }
            names.Add(memberExpression.Member.Name);
            return names;
        }
    }

使い方

HtmlHelper.cs
        public static MvcHtmlString ImageLinkFor<TModel, TProperty>(this HtmlHelper<TModel> helper, Expression<Func<TModel, TProperty>> expression)
        {
            var propertyNames = expression.GetPropertyNames();
/*色々処理*/
        }
Index.cshtml

@Html.ImageLinkFor(x=>x.Image)

2
5
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
2
5

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?