Reputation: 1617
I wrote some code below:
public IEnumerable<Photo> GetPhotos(int page, int pageSize, string userId = null, OrderBy orderBy = OrderBy.TimeOfCreation)
{
var c = Database.Set<Photo>().Where(p => string.IsNullOrEmpty(userId) || p.ClientProfileId == userId);
c = orderBy == OrderBy.TimeOfCreation ?
c.OrderBy(p => p.TimeOfCreation).Skip((page - 1) * pageSize).Take(pageSize) :
c.OrderBy(p => p.AverageRaiting).Skip((page - 1) * pageSize).Take(pageSize);
return c
}
Is it possible to do it all in one statement and to get rid of the repetitious code?
Upvotes: 2
Views: 99
Reputation: 35780
You can move the condition inside OrderBy
:
var c = Database.Set<Photo>().
Where(p => string.IsNullOrEmpty(userId) || p.ClientProfileId == userId).
OrderBy(p => orderBy == OrderBy.TimeOfCreation ? p.TimeOfCreation : DateTime.Now).
ThenBy(p => orderBy == OrderBy.AverageRaiting ? p.AverageRaiting : 0.0).
Skip((page - 1) * pageSize).Take(pageSize);
return c
Upvotes: 2
Reputation: 38468
You can assign OrderBy
result back to the same variable:
var c = Database.Set<Photo>().Where(p => string.IsNullOrEmpty(userId) || p.ClientProfileId == userId);
c = orderBy == OrderBy.TimeOfCreation
? c.OrderBy(p => p.TimeOfCreation)
: c.OrderBy(p => p.AverageRaiting);
return c.Skip((page - 1) * pageSize).Take(pageSize)
Upvotes: 4