0

I have a website that used to use a lot of methods to get lists from my data context. I have recently began changing those to generic methods to cut down on code; however, a lot of the methods have me doing an OrderBy before I return the list. This is what I'm using for my generic method already.

public List<TEntity> GetObjects<TEntity>()
    where TEntity : class
{
    return this.dataContext.Set<TEntity>().ToList();
}

I would like, if it's possible, to have something similar to this, where I can pass in the name of the variable I would like the list to be sorted by, and use that to sort the list before the generic method returns it. Maybe something along the lines of:

public List<TEntity> GetObjects<TEntity>(string orderedVariable)
    where TEntity : class
{
    // Code to get information about the property of the class
    return this.dataContext.Set<TEntity>()OrderBy(// Code to sort the list).ToList();
}
  • It depends how generic. You could do something like: `GetObjects(Func orderClause)` then `.Set().Orderby(orderClause).ToList();` Something along those lines. But if you just want to pass in strings you can do some reflection shenanigans to work out the property. Albeit, I have never seen that turn out pretty. – Heinrich Jun 03 '21 at 00:53
  • 1
    Potentially answered here? https://stackoverflow.com/questions/1689199/c-sharp-code-to-order-by-a-property-using-the-property-name-as-a-string – Will Jun 03 '21 at 00:58
  • I'll definitely try those out when I can. Right now, dotnet doesn't even let me use the --help command without crashing, so I'll have to wait for that to be fixed – Dakota Worzella Jun 03 '21 at 01:04
  • Does the caller know which property they want? or do you need the end user to choose? Do you want to sort by properties of owned types? – Jeremy Lakeman Jun 03 '21 at 01:08
  • @Will that solution is a LinqToObject solution. I suspect OP wants a LinqToEF solution. – Aron Jun 03 '21 at 04:16

1 Answers1

1

Try to use nuget package System.Linq.Dynamic.Core (https://dynamic-linq.net/overview) and you can pass just string to orderBy method. for example that how it looks in our generic method.

query.OrderBy(input.Sorting ?? "id asc")

it accepts a string from generic input or if it null we order with Id column by default.

grinay
  • 709
  • 1
  • 6
  • 21