vendredi 22 octobre 2021

Finding a property name within a lambda expression

I have a coding problem to solve, I kind of know the path I should be following, but there is still something missing. I got a mission to change a code to make it more generic and reduce the redundance.

The whole class is given below. It seems a bit dummy, the question is the redundance itself.

using System; 
using System.Collections.Generic;
using System.Linq;
using System.Reflection;

namespace TestRedundance
{
    public class EntityRedundance
    {
        public class Entity
        {
            public int Id { get; set; }
            public string Name { get; set; }
            public string Description { get; set; }
            public DateTime ValidFrom { get; set; }
        }

        private void AddSorting(IQueryable<Entity> query, List<string> sortingColumns, bool orderDescending)
        {

            if (!sortingColumns.Any())
            {
                query = query.OrderBy(x => x.Name);
                return;
            }

            foreach (var column in sortingColumns)
            {

                switch (column)
                {

                    case "Name":
                        query = orderDescending ? query.OrderByDescending(x => x.Name) : query.OrderBy(x => x.Name);
                        break;
                    case "Description":
                        query = orderDescending ? query.OrderByDescending(x => x.Description) : query.OrderBy(x => x.Description);
                        break;
                    case "ValidFrom":
                        query = orderDescending ? query.OrderByDescending(x => x.ValidFrom) : query.OrderBy(x => x.ValidFrom);
                        break;

                }
            }
        }
    }
}

As far as I understood, the redundance is on repeting the same exact code in each switch case condition, changing only the column to be sorted by.

My intention was to change it to a single line, comparing the property name of my entity with the column name, using Reflection, and then replacing the switch-case block for this single line. But the lambda expression does not allow me to do that. Something like the line below, which is commented because it's sintax is wrong.

//query = orderDescending ? query.OrderByDescending(x => 
//x.GetType().GetProperties() : query.OrderBy(x => x.Name);

I would appreciate any suggestions.

Many thanks.





Aucun commentaire:

Enregistrer un commentaire