I have this switch with select
switch (sorting)
{
case "newest":
{
var userId = User.Identity.GetUserId();
var model = db.Posts.Include(p => p.Vote)
.OrderByDescending(p => p.PostId).ToList()
.Select(p => new ListPostsViewModel
{
UserVotedUpOnPost = p.Vote.Any(u => u.ApplicationUserID == userId && u.PostVote == 1),
UserVotedDownOnPost = p.Vote.Any(u => u.ApplicationUserID == userId && u.PostVote == -1),
PostId = p.PostId.ToString(),
TimeAgo = ToRelativeDate(p.MessageDate),
Message = p.Message,
TotalVotes = p.Vote.Sum(v => v.PostVote)
}).ToList();
return View("Index", model);
} break;
case "oldest":
{
var userId = User.Identity.GetUserId();
var model = db.Posts.Include(p => p.Vote)
.OrderBy(p => p.PostId).ToList()
.Select(p => new ListPostsViewModel
{
UserVotedUpOnPost = p.Vote.Any(u => u.ApplicationUserID == userId && u.PostVote == 1),
UserVotedDownOnPost = p.Vote.Any(u => u.ApplicationUserID == userId && u.PostVote == -1),
PostId = p.PostId.ToString(),
TimeAgo = ToRelativeDate(p.MessageDate),
Message = p.Message,
TotalVotes = p.Vote.Sum(v => v.PostVote)
}).ToList();
return View("Index", model);
}
break;
}
As you can see, the only line that is different is .OrderByDescending(p => p.PostId).ToList()
and I will have a few more similar but how can I write it without duplicate all the code in the select etc?