So i want to slice a "IQueryable" in C# ASP.NET Web Api but i can't make it work. With the code below it might get more clear what i want to do.
private TestTwoContext db = new TestTwoContext();
// GET: api/Fruits/thefruits
[HttpGet]
[Route("api/Fruits/thefruits")]
public IQueryable<Fruits> TheFruits()
{
dynamic myList = db.Fruits;
var FiveItems = Queryable.Take(Queryable.Skip(myList, 5), 5);
return FiveItems;
}
this gives me error in browser console:
jquery-3.3.1.min.js:2 GET http://localhost:49771/api/Fruits/thefruits 500 (Internal Server Error)
i need to cut my list (db.Fruits) from the 5th element to the 10th element. Just like we slice arrays in JavaScript. Example:
var myList = array.slice(5, 10)
I have also tried this:
private TestTwoContext db = new TestTwoContext();
// GET: api/Fruits/thefruits
[HttpGet]
[Route("api/Fruits/thefruits")]
public IQueryable<Fruits> TheFruits()
{
var myList = db.Fruits;
var FiveItems = myList.Skip(5).Take(4);
return FiveItems;
}
this gives me error in browser console: jquery-3.3.1.min.js:2 GET http://localhost:49771/api/Fruits/thefruits 500 (Internal Server Error)
the number in skip and take will be passed as parametars but that is not that part i am worried about... those number are just example for now. Any help would be appreciated.
This Conroler works without problems:
// GET: api/Fruits
public IQueryable<Fruits> GetFruits()
{
return db.Fruits;
}
returns the whole list of fruits, which later i write it down in table in HTML.
This also works :
[HttpGet]
[Route("api/Fruits/thefruits")]
public IQueryable<Fruits> TheFruits()
{
var myList = db.Fruits;
var FiveItems = myList.Take(5);
return FiveItems;
}
but it gives me the the first 5 elements... not from the 5th to 10th element.
Try updating your "TheFruits" method to the following:
Sample Console app:
This is what i had to do to make it work:
Try this to understand Skip() and Take().
Skip(X) -> It ignores the first X items on the Iqueryable
Take(Y) -> Limits the max resultant results.
OUTPUT IS:
It would be nice if you posted the 500 error but as a guess, it's probably because cannot
Skip
without calling an order by in EntityFramework