LINQ和MVC控制器查询

时间:2014-09-28 13:07:09

标签: asp.net-mvc linq

嗨这应该是一个非常简单的问题,与我不同的实际LINQ知识!我想只返回最后20条记录,通常是。在按降序排序时选择(20),但因为我正在返回模型的实例.CPU我不知道在哪里放置语句。 / p>

帮助将不胜感激,谷歌搜索过去一小时左右。

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

1 个答案:

答案 0 :(得分:1)

你可以

  • 订购查询(desc),然后选择您的Models.CPU类,并将take(20)作为最后一个语句
  • 在使用.ToList()之前(在对db执行查询之前)订购结果

e.g。

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