【问题标题】:LINQ and MVC controller queryLINQ 和 MVC 控制器查询
【发布时间】:2014-09-28 22:55:22
【问题描述】:

您好,这应该是一个与我不同的实际 LINQ 知识的非常简单的问题!我只想返回最后 20 条记录,通常是 .Take(20) 当按降序排序时,但因为我返回的是 model.CPU 的一个实例,所以我不知道该把语句放在哪里。

非常感谢您的帮助,过去一个小时左右一直在谷歌搜索。

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

【问题讨论】:

  • 为什么降序和Take(20) 不起作用?

标签: asp.net-mvc linq


【解决方案1】:

你可以

  • 对查询进行排序 (desc),然后选择您的 Models.CPU 类,并将 take(20) 作为最后一条语句
  • 在使用 .ToList() 之前对结果排序(在对数据库执行查询之前)

例如

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

【讨论】:

  • 非常感谢。那行得通,只需将 Desc 更改为 Descending 即可。我遇到了问题,因为我习惯于在 select 之后使用 take 方法,例如: var lastFiveProducts = (from p in products orderby p.ProductDate descending select p).Take(5);
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2016-03-12
  • 1970-01-01
  • 2010-10-21
  • 1970-01-01
  • 1970-01-01
  • 2017-02-08
  • 2022-01-15
相关资源
最近更新 更多