Question

Why this method does not sort values from list?

public Paging(IEnumerable<T> values, int start, int limit, string property, string dir)
        {
            this.Total = values.Count();

            Func<T, string> func = a => a.GetType().GetProperty(property).Name;

            IEnumerable<T> order = null;

            if (dir == "DESC")
                order = values.OrderByDescending(func);
            else
                order = values.OrderBy(func);

            if ((start + limit) > this.Total)           
                limit = this.Total - start;

            IEnumerable<T> items = (start < 0 || limit < 0) ? order : order.Skip(start).Take(limit);

            this.AddRange(items);
        }       
Was it helpful?

Solution

You are sorting by the property name, which is the same for every element in the collection. This expression will always return property.

a => a.GetType().GetProperty(property).Name

If you sort by an expression that is constant across the entire collection, it has no effect.

Regardless, using reflection inside of a sort is a very bad idea because of the extreme overhead it will cause to execute the sort. I would recommend using Dynamic LINQ, which has the built-in functionality to sort by a property given by name.

If you add the Dynamic LINQ library to your project, you would be able to write this instead:

if (dir == "DESC")
    order = values.OrderBy(property + " DESC");
else
    order = values.OrderBy(property);
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top