2014-09-28 61 views
0

嗨,這應該是一個非常簡單的問題,與我的實際LINQ知識!我只想返回最後20條記錄,通常情況下.Take(20)在按降序排列時按順序排列,但因爲我返回了model.CPU的實例,所以我不知道在哪裏放置語句。LINQ和MVC控制器查詢

幫助將不勝感激,谷歌過去一個多小時左右。

using System; 
using System.Collections.Generic; 
using System.Linq; 
using System.Web; 
using System.Web.Http; 

namespace hello_services.Controllers 
{ 
    public class cpuController : ApiController 
    { 
     private Data.ResourceDataModelDataContext _context = new Data.ResourceDataModelDataContext(); 

     //WebAPI will respond to an HTTP GET with this method 
     public List<Models.CPU> Get() 
     { 
      //get all of the records from the Counter_CPU table 
      var cpuRecords = from e in _context.Counter_CPUs 
          select new Models.CPU 
          { 
           Counter_CPU_ID = e.Counter_CPU_ID, 
           //Counter_CPU_Time = e.Counter_CPU_Time, 
           Counter_CPU_Percentage = e.Counter_CPU_Percentage 
          }; 


      return cpuRecords.ToList(); 
     } 
    } 
} 
+0

爲什麼降序和'Take(20)'不起作用? – David 2014-09-28 13:14:53

回答

1

可以

  • 訂單查詢(遞減),然後用取(20)最後的陳述
  • 爲了使用.ToList之前,你的結果選擇Models.CPU類() (在db上執行查詢之前)

eg

return cpuRecords.OrderByDesc(o => o.Counter_CPU_ID).Take(20).ToList(); 
+0

非常感謝你。這工作,只需要改變降序降序。 我是有,因爲我習慣使用take方法剛過問題選擇 如: VAR lastFiveProducts =(從商品P 的OrderBy p.ProductDate降序 選擇P)。取(5) ; – 2014-09-28 13:30:09