2016-10-24 51 views
-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(),我都會有幾個類似的,但我怎麼能寫出來,而不復制所有代碼的選擇等等?

+0

'VAR數據= db.Posts.Include(p值=> p.Vote);'然後交換機語句來訂購它 - '案 「最新的」:數據=數據。 OrderBy(...)'等,最後'var model = data.Select(....' –

回答

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);