I am attempting to write a generic sort extension method to List based on a string column name and linq.
I have most of it here, but it doesn't work just yet. 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;
}
Stepping through this code I see that list is sorted properly, but when returned, it has no effect on the list I passed in. I'm guessing AsQueryable or OrderBy is creating a new object in memory and I'm no longer pointing to the same reference. Does anyone have some tips on how to make this work appropriately, or barring that, another solution? Thanks!
It's a different list. The ToList()
call creates a new List<T>
instance, entirely separate from the List<T>
that was passed into the method. It will have the same items in it, probably in a different order, but the list itself is a different object.
By the way, dynamic linq already does this so you might want to check it out. You can start reading about it here.
Does anyone have some tips on how to make this work appropriately, or barring that, another solution?
If you want to modify the original list, use List<T>.Sort
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With