我有一个List< User>收集,并希望使用开始和结束索引进行内存中分页。
最好的方法是什么?
答案 0 :(得分:17)
list.Skip(pageIndex * pageSize).Take(pageSize);
假设一个基于0的pageIndex。或者如果你真的有一个结束索引:
list.Skip(startIndex).Take(endIndex - startIndex);
答案 1 :(得分:5)
这个代码示例足够吗?你的问题不是很详细,但这基本上就是你的做法。
// fill this in
int pageSize = 10;
// This figures out the total number of pages for you. The modulo stuff
// takes care of the case when the last page has less than pageSize items.
// It's the same as Math.Ceiling() but using integers.
int numberOfPages = (aList.Count / pageSize)
+ (aList.Count % pageSize == 0 ? 0 : 1);
// 0 based
int currentPage = 0;
IEnumerable<SomeType> itemsOnThisPage = aList.Skip(currentPage * pageSize).Take(pageSize);
答案 2 :(得分:2)
使用Linq 方便但不具备性能。我会选择经典之作:
const int ItemPerPage = 20;
int pageNo = 5;
for (int i = pageNo * ItemPerPage; i < (pageNo * (ItemPerPage + 1)); i++)
{
Console.WriteLine(items[i]);
}
答案 3 :(得分:0)
假设您使用的是.NET 3.5+,可以使用linq执行此操作: http://solidcoding.blogspot.com/2007/11/paging-with-linq.html
答案 4 :(得分:0)
这可能符合您的需求。我试图让它按要求使用开始和结束索引。呼叫 像GetPages(myusers,10);预览10件。
public IEnumerable<IEnumerable<T>> GetPages<T>(
IList<T> source, int pageLength)
{
//validation here
for (int startIndex = 0;
startIndex < source.Count;
startIndex += pageLength)
{
yield return Page(source, startIndex, pageLength);
}
}
public IEnumerable<T> GetPage<T>(
IList<T> source, int startIndex, int length)
{
//validation here
for (int i = startIndex;
i < startIndex + length && i < source.Count;
i++)
{
yield return source[i];
}
}
然后做
List<IEnumerable<User>> pages = GetPages(myusers, 10).ToList();
现在您可以索引页面(基于0)