我正在处理尝试在 C# 2.0 中实现 IEnumerable(和 ICollection)的自定义集合类中的项目块。例如,假设我一次只想要 1000 件物品,而我的收藏中有 3005 件物品。我有一个可行的解决方案,我在下面演示,但它看起来很原始,我认为必须有更好的方法来做到这一点。
这是我所拥有的(例如,我使用 C# 3.0 的 Enumerable 和 var,只需将这些引用替换为您心中的自定义类):
var items = Enumerable.Range(0, 3005).ToList();
int count = items.Count();
int currentCount = 0, limit = 0, iteration = 1;
List<int> temp = new List<int>();
while (currentCount < count)
{
limit = count - currentCount;
if (limit > 1000)
{
limit = 1000 * iteration;
}
else
{
limit += 1000 * (iteration - 1);
}
for (int i = currentCount; i < limit; i++)
{
temp.Add(items[i]);
}
//do something with temp
currentCount += temp.Count;
iteration++;
temp.Clear();
}
任何人都可以在 C# 2.0 中提出一种更优雅的方法吗?我知道这个项目是否来自过去 5 年,我可以使用 Linq(如这里和这里所示)。我知道我的方法会起作用,但我不想让我的名字与如此丑陋的(在我看来)代码相关联。
谢谢。