Paul Read
Paul Read

Reputation: 1

LINQ and MVC controller query

Hi this should be a really simple problem with actual LINQ knowledge unlike me! I want to return only the last 20 records and normally .Take(20) when ordered by descending works but because I'm returning an instance of the model.CPU I don't know where to put the statement.

Help would be greatly appreciated, have been Googling for the past hour or so.

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

Upvotes: 0

Views: 1096

Answers (1)

kapsiR
kapsiR

Reputation: 3196

You can

  • Order the query (desc) and then select your Models.CPU class with take(20) as last statement
  • Order your result before using the .ToList() (before executing the query on the db)

e.g.

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

Upvotes: 1

Related Questions