Sve*_*sen 2 c# collections c#-2.0
我正在尝试在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();
}
Run Code Online (Sandbox Code Playgroud)
任何人都可以在C#2.0中建议更优雅的方式吗?我知道这个项目是否是过去5年我可以使用Linq(如此处和此处所示).我知道我的方法会起作用,但我不想让我的名字与这种丑陋(在我看来)的代码相关联.
谢谢.
首先 .yield是你的朋友,它是2.0引入的.考虑:
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;
}
Run Code Online (Sandbox Code Playgroud)
然后我们在类型和大小上都很灵活,所以它可以很好地重复使用.唯一被限制为2.0的意思是,我们不能使它成为一种扩展方法.
| 归档时间: |
|
| 查看次数: |
760 次 |
| 最近记录: |