Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I improve this sorting code? [closed]

Tags:

c#

.net

linq

I'm checking the sort parameter and building a bunch of if statements:

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 do I make this better?

like image 753
Rod Avatar asked May 11 '12 19:05

Rod


2 Answers

Separate your ordering and the rest of the query - the parts that are the same for each query you don't have to duplicate in your codebase (keep it 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();
like image 62
BrokenGlass Avatar answered Nov 03 '22 07:11

BrokenGlass


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();
like image 26
mattytommo Avatar answered Nov 03 '22 05:11

mattytommo