gpt4 book ai didi

c# - 使用 LINQ 分页对象列表

转载 作者:行者123 更新时间:2023-11-30 22:04:50 24 4
gpt4 key购买 nike

我有一个对象列表 List<Parent> Parents .

Parent类有一个 List<Child> Children .

到目前为止,我已经将分页应用于Parents使用 LINQ:

List<Parent> PageX = Parents.Skip(PageIndex * PageSize).Take(PageSize);

例如,如果 PageSize=2,我有以下结果:

--------------- Page 1 ----------------------

Parent 1

Child 1

Child 2

Child 3

Parent 2

Child 1

Child 2

--------------- Page 2 ----------------------

Parent 3

Child 1

Parent 4

Child 1

Child 2

我想要实现的是:

--------------- Page 1 ----------------------

Parent 1

Child 1

Child 2

--------------- Page 2 ----------------------

Child 3

Parent 2

Child 1

--------------- Page 3 ----------------------

Child 2

Parent 3

Child 1

我怎样才能做到这一点?

最佳答案

你可以使用 SelectMany :

var page = parents.SelectMany(p => p.Children)
.Skip(PageIndex * PageSize).Take(PageSize);

查看工作 fiddle here .

更新:
我做了一些研究,因为这也让我感兴趣。使用以下假设:

  • 您正在使用 EF
  • 你只有一级的父->子关系
  • 你的实体都有一个Position属性

您应该能够对数据库执行以下操作,以“在一个查询中”以正确的顺序获取页面的项目:

var pageItems = db.Parents.SelectMany(p => p.Children).Include(c => c.Parent)
.OrderBy(c => c.Parent.Position).ThenBy(c => c.Position)
.Skip(PageIndex * PageSize).Take(PageSize);

我没有测试这段代码,因为我现在没有数据库来测试它,所以如果你能测试它,如果假设对你的情况来说是正确的,请报告回来。

关于c# - 使用 LINQ 分页对象列表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24865223/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com