How to define the order of a list dynamically using Linq and C #

0
Hello, I'm creating a method so that I can return a list of people where, I pass the column that should be sorted and whether it is increasing or decreasing. So:

public async Task<List<Pessoa>> getAsync() => await getAsync("id", false);
public async Task<List<Pessoa>> getAsync(string order) => await getAsync(order, false);
public async Task<List<Pessoa>> getAsync(string order, bool desc)
{
    using (var context = Context())
    {
        try
        {
            var list = context.ContaBancaria.AsNoTracking();

            return desc ? 
                await list.OrderByDescending(x => x.GetType().GetProperty(order))
                    .ToListAsync() :
                await list.OrderBy(x => x.GetType().GetProperty(order))
                    .ToListAsync();

            }
        catch
        {
            return null;
        }
    }
}

My question is whether there is any way I can sort the list (ie, use the OrderBy or the OrderByDescending method in a more "dynamic" way than this?)

NOTE: When I say dynamic, I say in code economy. I thought about creating a OrderBy method that would accept one more field, this being the reference of increasing or decreasing and in that method to do the treatment. So its use would be something like this:

public async Task<List<Pessoa>> getAsync() => await getAsync("id", false);
public async Task<List<Pessoa>> getAsync(string order) => await getAsync(order, false);
public async Task<List<Pessoa>> getAsync(string order, bool desc)
{
    using (var context = Context())
    {
        try
        {
            var list = context.ContaBancaria.AsNoTracking();

            return await list
                .OrderBy(x => x.GetType().GetProperty(order), desc)
                .ToListAsync();
        catch
        {
            return null;
        }
    }
}
    
asked by anonymous 07.08.2018 / 23:22

0 answers