Why does the Linq OrderBy extension not affect the list it is called on?

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!

+6
source share
3 answers

This is a different list. Calling ToList() creates a new List<T> instance, completely isolated from List<T> , which was passed to the method. It will have the same elements, possibly in a different order, but the list itself is a different object.

By the way, dynamic linq already does this, so you can check it out. You can start reading about it here .

+10
source

Does anyone have any tips on how to make this work appropriately or to prohibit it, another solution?

If you want to change the original list, use List<T>.Sort .

+6
source

One of the main ideas of LINQ is that it does not modify the things it invokes.

OrderBy() can be called on any IEnumerable<T> , even those that are not backed up by anything resembling a list (for example, it is generated "on the fly"). And it would be really inconsistent if he did something like: "If the source is IList<T> , sorts it and returns the original link. If it is not, a new sorted sequence is created."

+2
source

Source: https://habr.com/ru/post/892350/


All Articles