D
D
Daeamon2017-10-02 20:59:41
ASP.NET
Daeamon, 2017-10-02 20:59:41

How to shorten Dynamic LINQ Order BY record?

Func<Article, Object> orderByFunc = null;
            switch (OrderBy)
            {
                case "AuthorID":
                    orderByFunc = ob => ob.AuthorID;
                    break;
                case "Created":
                    orderByFunc = ob => ob.Created;
                    break;
                case "Title":
                    orderByFunc = ob => ob.Title;
                    break;
                default:
                case "ID":
                    orderByFunc = ob => ob.ID;
                    break;
            }

            List<Article> ArticlesList = new List<Article>();
            switch (OrderWay)
            {
                default:
                case "DESC":
                    ArticlesList = getDB().Article.OrderByDescending(orderByFunc).Skip(Page * Limit).Take(Limit).ToList();
                    break;
                case "ASC":
                    ArticlesList = getDB().Article.OrderBy(orderByFunc).Skip(Page * Limit).Take(Limit).ToList();
                    break;
            }

Is there such a code, is it possible to somehow reduce switch-and in a couple of lines? (Do not write every time "orderByFunc = ob => ob.FieldName", but write once orderByFunc = someUnknownFunctionToGetFieldFromAnyClass(OrderBy)) The variable "OrderBy" always corresponds to the name fields for sorting.

Answer the question

In order to leave comments, you need to log in

1 answer(s)
S
Sanostee, 2017-10-02
@Daeamon

Func<Article, object> orderByFunc = (a) => 
   typeof(Article).GetProperty(OrderBy).GetValue(a);

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question