WEB API IQueryable skip() take()



所以我想在 C# ASP.NET Web API 中切片一个"IQueryable",但我无法让它工作。使用下面的代码,可能会更清楚地了解我想做什么。

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

这在浏览器控制台中给我带来了错误:

jquery-3.3.1.min.js:2 GET http://localhost:49771/api/Fruits/thefruits 500 (内部服务器错误(

我需要削减我的列表(db。水果(从第5元素到第10元素。 就像我们在 JavaScript 中对数组进行切片一样。 例:

var myList = array.slice(5, 10)

我也试过这个:

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

这在浏览器控制台中给我带来了错误: jquery-3.3.1.min.js:2 GET http://localhost:49771/api/Fruits/thefruits 500 (内部服务器错误(

跳过和采取中的数字将作为参数传递,但这不是我担心的部分......这些数字目前只是例子。任何帮助将不胜感激。

这个协调器工作没有问题:

// GET: api/Fruits
public IQueryable<Fruits> GetFruits()
{
return db.Fruits;
}

返回整个水果列表,稍后我将其写在 HTML 表中。

这也有效:

[HttpGet]
[Route("api/Fruits/thefruits")]
public IQueryable<Fruits> TheFruits()
{
var myList = db.Fruits;
var FiveItems = myList.Take(5);
return FiveItems;
}

但它给了我前 5 个元素......不是从第 5 个元素到第 10 个元素。

如果您发布 500 错误会很好,但作为猜测,这可能是因为如果不在 EntityFramework 中调用订单就无法Skip

[HttpGet]
[Route("api/Fruits/thefruits")]
public IQueryable<Fruits> TheFruits()
{
return db.Fruits.OrderBy(x => x.Id).Skip(4).Take(5);
}

试试这个来理解 Skip(( 和 Take((。

var list = new List<long>{0,1,2,3,4,5,6,7,8,9};
var secondList = list.AsQueryable().Skip(5).Take(5).ToList();
secondList

跳过(X( -> 它忽略 Iqueryable 上的前 X 项

Take(Y( -> 限制最大结果结果。

输出为:

List<long>(5) { 5, 6, 7, 8, 9 }

尝试将"TheFruits"方法更新为以下内容:

// GET: api/Fruits/thefruits
[HttpGet]
[Route("api/Fruits/thefruits")]
public IQueryable<Fruits> TheFruits()
{
dynamic myList = db.Fruits;
var FiveItems = myList.Skip(5).Take(5);
return FiveItems;
}

示例控制台应用:

using System.Linq;
static void Main(string[] args)
{
int[] test = new[] { 1, 2, 3, 4, 5, 6, 7, 8 };
var t = test.AsQueryable().Skip(5).Take(5);
foreach (int i in t)
{
Console.WriteLine(i.ToString());
}
Console.ReadLine();
}

这是我必须做的才能使其工作:

[HttpGet]
[Route("api/Fruits/thefruits")]
public List<Fruits> TheFruits()
{
var myList = db.Fruits;
var FiveItems = myList.AsEnumerable().Skip(5).Take(5).ToList();
return FiveItems;
}

最新更新