Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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!

like image 734
IronicMuffin Avatar asked Jul 08 '11 18:07

IronicMuffin


2 Answers

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.

like image 94
Kent Boogaart Avatar answered Sep 19 '22 13:09

Kent Boogaart


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.

like image 34
jason Avatar answered Sep 22 '22 13:09

jason