-1
我有這個開關,選擇減少選擇開關中的代碼重複?
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;
}
正如你所看到的,是不同的唯一線路.OrderByDescending(p => p.PostId).ToList()
,我都會有幾個類似的,但我怎麼能寫出來,而不復制所有代碼的選擇等等?
'VAR數據= db.Posts.Include(p值=> p.Vote);'然後交換機語句來訂購它 - '案 「最新的」:數據=數據。 OrderBy(...)'等,最後'var model = data.Select(....' –