1

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); } 
0

1 Answer 1

1

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); 
Sign up to request clarification or add additional context in comments.

1 Comment

OrderByDescending does not exist. Use order = values.OrderBy(property + " DESC"); or order = values.OrderBy(property);

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.