我正在使用 Troy Goode's paged List在我的项目中。
通常你只需给它一个 IEnumerable、一个 startindex 和一个项目计数就可以了。
但是,现在我正在尝试向它提供一个我生成的 IEnumerable,如下所示:
private static IEnumerable<Color> GetColors(Query query)
{
IndexSearcher searcher = new IndexSearcher(luceneIndexpath);
Hits hitColl = searcher.Search(query);
//Get all the unique colorId's
List<int> ids = new List<int>();
int id = 0;
for (int i = 0; i < hitColl.Length(); i++)
{
if (Int32.TryParse(hitColl.Doc(i).GetField("id").StringValue(), out id))
ids.Add(id);
}
foreach (int uniqueId in ids.Distinct<int>())
{
yield return ColorService.GetColor(uniqueId);
}
}
--编辑-- pagedList 有效,但请求我所有 Color 对象的产量,而不仅仅是分页对象。这当然会破坏 PagedList 的整体使用,并可能导致大量枚举。
--编辑--
我想我需要的是一种实现 Count() 的方法,这样我就可以让它从 ids.Distinct(int) 返回计数,而不是通过 ColorService.GetColor() 创建所有对象,然后计算该列表。
最佳答案
1) PagedList 将根据数据的外观对您的数据进行至少两次迭代 - 一次用于计数,然后一次用于获取正确的页面。确保这不会把事情搞砸 - 或者考虑在列表或其他一些“廉价”缓冲区中缓存以避免必须查询两次。
2) 如果您调用 ToList()
在将生成的结果传递给分页列表之前,它看起来正确吗?
3) 如果你只是使用你的 GetColors()
方法并转储它产生的所有内容,那 看起来正确吗?
基本上,您需要尝试确定问题出在 GetColors、PagedList 还是两者之间的交互。
编辑:“捷径”Count() 的唯一方法是实现 IList
或 IList<T>
.但是,到那时您要么必须正确地执行它,要么只是覆盖 Count
并实现 IEnumerable
再次。我想调用ToList()
并且使用结果可能会快得多,除非你真的有一个你不想保留在内存中的大量列表。
关于c# - 我怎样才能使我产生的 IEnumerable 与 PagedList 一起工作,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/553035/