在不使用Linq的情况下分页通用集合

时间:2020-03-05 18:41:47  来源:igfitidea点击:

我有一个System.Generic.Collections.List(Of MyCustomClass)类型的对象。

给定整数变量的页面大小和页面编号,如何仅收集" MyCustomClass"对象的任何单个页面?

这就是我所拥有的。我该如何改善?

'my given collection and paging parameters
Dim AllOfMyCustomClassObjects As System.Collections.Generic.List(Of MyCustomClass) = GIVEN
Dim pagesize As Integer = GIVEN
Dim pagenumber As Integer = GIVEN

'collect current page objects
Dim PageObjects As New System.Collections.Generic.List(Of MyCustomClass)
Dim objcount As Integer = 1
For Each obj As MyCustomClass In AllOfMyCustomClassObjects
If objcount > pagesize * (pagenumber - 1) And count <= pagesize * pagenumber Then
    PageObjects.Add(obj)
End If
objcount = objcount + 1
Next

'find total page count
Dim totalpages As Integer = CInt(Math.Floor(objcount / pagesize))
If objcount Mod pagesize > 0 Then
totalpages = totalpages + 1
End If

解决方案

回答

我们可以在IEnuramble实现集合上使用GetRange:

List<int> lolInts = new List<int>();

for (int i = 0; i <= 100; i++)
{
    lolInts.Add(i);
}

List<int> page1 = lolInts.GetRange(0, 49);
List<int> page2 = lilInts.GetRange(50, 100);

我相信我们可以弄清楚如何使用GetRange从此处获取单个页面。

回答

Generic.List应该提供Skip()和Take()方法,因此我们可以执行以下操作:

Dim PageObjects As New System.Collections.Generic.List(Of MyCustomClass)
PageObjects = AllOfMyCustomClassObjects.Skip(pagenumber * pagesize).Take(pagesize)

如果我们在2.0 Framework上表示"没有Linq",则我不认为List(Of T)支持这些方法。在这种情况下,请像乔纳森(Jonathan)建议的那样使用GetRange。