问题描述
我正在处理尝试在C#2.0中实现IEnumerable(和ICollection)的自定义集合类中的项目。比方说,我一次只需要1000个项目,我的收藏中有3005个项目。我有一个工作的解决方案,我在下面演示,但它似乎很原始,我认为有一个更好的方法来做这个。
I am dealing with trying to chunk up items in a custom collection class that implements IEnumerable (and ICollection) in C# 2.0. Let's say, for example, that I only want 1000 items at a time and I have 3005 items in my collection. I've got a working solution that I demonstrate below, but it seems so primitive that I figure there has to be a better way to do this.
这是我有(例如,我使用C#3.0的Enumerable和var,只是在你心目中用自定义类替换这些引用):
Here's what I have (for example's sake, I'm using C# 3.0's Enumerable and var, just replace those references with a custom class in your mind):
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(如演示和)。我知道我的方法会工作,但我不想让我的名字与这样丑陋的(在我看来)代码相关联。
Can anyone suggest a more elegant way of doing this in C# 2.0? I know if this project was from the past 5 years I could use Linq (as demonstrated here and here). I know my method will work, but I'd rather not have my name associated with such ugly (in my opinion) code.
谢谢。 $ b
推荐答案
首先。 yield
是你的朋友,它是用2.0介绍的。考虑:
Firstly . yield
is your friend here, and it was introduced with 2.0. Consider:
public static IEnumerable<List<T>> Chunk<T>(IEnumerable<T> source, int chunkSize)
{
List<T> list = new List<T>(chunkSize);
foreach(T item in source)
{
list.Add(item);
if(list.Count == chunkSize)
{
yield return list;
list = new List<T>(chunkSize);
}
}
//don't forget the last one!
if(list.Count != 0)
yield return list;
}
然后我们灵活的类型和大小,所以它是很好的可重复使用。唯一被限制为2.0意味着,我们不能使它成为一个扩展方法。
Then we're flexible in type and size, so it's nicely reusable. The only that being restricted to 2.0 means, is that we can't make it an extension method.
这篇关于Chunk IEnumerable / ICollection Class C#2.0的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!