I'm using something like this (via Reflection):
public static class RepoHelper<T> where T: class
{
public static List<T> SortBy(List<T> lista, string fieldName, bool ascending = true)
{
Type t = typeof(T);
PropertyInfo pi = t.GetProperty(fieldName);
if (ascending)
lista = lista.OrderBy(x => pi.GetValue(x, null)).ToList();
else
lista = lista.OrderByDescending(x => pi.GetValue(x, null)).ToList();
return lista;
}
}
Usage:
List<Foo> foos = GetFoo();
foos = RepoHelper<Foo>.SortBy(foos, "Name");
foos = RepoHelper<Foo>.SortBy(foos, "ID", false);
You can test it here:
RepoHelper | C# Online Compiler | .NET Fiddle[
^]