提问人:Zack Peterson 提问时间:8/22/2008 最后编辑:arbZack Peterson 更新时间:5/3/2012 访问量:1201
对不带 Linq 的泛型集合进行分页
Page a Generic Collection Without Linq
问:
我有一个System.Generic.Collections.List(Of MyCustomClass)类型对象。
给定整数变量 pagesize 和 pagenumber,如何仅收集任何单页对象?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
答:
1赞
FlySwat
8/22/2008
#1
在 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 从这里抓取单个页面。
2赞
Adam Lassek
8/22/2008
#2
Generic.List 应该提供 Skip() 和 Take() 方法,因此您可以这样做:
Dim PageObjects As New System.Collections.Generic.List(Of MyCustomClass)
PageObjects = AllOfMyCustomClassObjects.Skip(pagenumber * pagesize).Take(pagesize)
如果您所说的“没有 Linq”是指在 2.0 框架上,我不相信 List(Of T) 支持这些方法。在这种情况下,请按照 Jonathan 的建议使用 GetRange。
下一个:清理 RTF 文本
评论