使用select减少交换机中的代码重复?

时间:2016-10-24 12:59:21

标签: asp.net-mvc-4 switch-statement redundancy

我选择了这个开关

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(),我会有一些更相似的但是如何在没有重复选择等所有代码的情况下编写它?

1 个答案:

答案 0 :(得分:1)

类似的东西:

var qry = db.Posts.Include(p => p.Vote);
select (sorting) {
  case "newest":
    qry = qry.OrderBy(x => x.Date);
    break;

  case "oldest":
    qry = qry.OrderByDescending(x => x.Date);
    break;
}
var res = qry.Select(p => new ListPostsViewModel {
                       …
                     });
 return View("Index, res);