How can I improve this sort code?

I check the sort parameter and build a bunch of if :

 if (sortDirection == "ASC") { if (sortBy == "Id") return customerList.OrderBy(x => x.Id).Skip(startIndex).Take(pageSize).ToList(); if (sortBy == "FirstName") return customerList.OrderBy(x => x.FirstName).Skip(startIndex).Take(pageSize).ToList(); if (sortBy == "City") return customerList.OrderBy(x => x.City).Skip(startIndex).Take(pageSize).ToList(); } else { if (sortBy == "Id") return customerList.OrderByDescending(x => x.Id).Skip(startIndex).Take(pageSize).ToList(); if (sortBy == "FirstName") return customerList.OrderByDescending(x => x.FirstName).Skip(startIndex).Take(pageSize).ToList(); if (sortBy == "City") return customerList.OrderByDescending(x => x.City).Skip(startIndex).Take(pageSize).ToList(); } 

How can I do it better?

+6
source share
3 answers

Separate your order and the rest of the request - the parts that are the same for each request that you do not need to duplicate in your code base (save DRY ):

 var query = customerList; if (sortDirection == "ASC") { if (sortBy == "Id") query = query.OrderBy(x => x.Id); ///and so on } query = query.Skip(startIndex).Take(pageSize).ToList(); 
+8
source

Use reflection :)

 customerList = (sortDirection == "ASC") ? customerList .OrderBy(x => x.GetType().GetProperty(sortBy).GetValue(x, null)) .Skip(startIndex) .Take(pageSize) .ToList() : customerList .OrderByDescending(x => x.GetType().GetProperty(sortBy).GetValue(x, null)) .Skip(startIndex) .Take(pageSize) .ToList(); 
+2
source

It looks like you just want to order by property name as a string. In this case, this is actually enabled using "Dynamic LINQ":

Dynamic LINQ OrderBy on IEnumerable <T>

Take a look at this question and it should provide you with sample code to solve your problem.

+1
source

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


All Articles