I am trying to write a generic sort extension method for a list based on row column name and linq.
I have a large part here, but so far this does not work. The logic is taken from this site .
public static List<T> Sort<T>(this List<T> list, string sortColumn, string sortOrder) { if (string.IsNullOrWhiteSpace(sortColumn)) return list; int order = sortOrder == "desc" ? -1 : 1; var param = Expression.Parameter(typeof(T), "x"); var sortExpression = Expression.Lambda<Func<T, object>>(Expression.Property(param, sortColumn), param); list = list.AsQueryable().OrderBy(sortExpression).ToList(); return list; }
By executing this code, I see that the list is sorted correctly, but when it returns, it does not affect the list I went to. I assume that AsQueryable or OrderBy creates a new object in memory, and I'm no longer pointing to the same link. Does anyone have any advice on how to do this job properly or to ban this, another solution? Thanks!
source share