gpt4 book ai didi

c# - block IEnumerable/ICollection 类 C# 2.0

转载 作者:行者123 更新时间:2023-11-30 19:18:34 25 4
gpt4 key购买 nike

<分区>

我正在处理尝试在自定义集合类中分块项目,该类在 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(如 herehere 所示)。我知道我的方法会奏效,但我不想让我的名字与这种丑陋的(在我看来)代码相关联。

谢谢。

25 4 0