.NET迭代通过在一个时间一个IEnumerable的几个要素 [英] .NET Iterate through an IEnumerable several elements at a time
问题描述
由于集合,我需要遍历所有元素三个(或其他金额)的时间。例如:
Given a collection, I need to iterate through all the elements three (or some other amount) at a time. For example:
string[] exampleData = {"John", "Doe", "1.1.1990", "Jane", "Roe", "2.2.1980"}
for(int i = 0; i < exampleData.Length; i += 3) {
CreateUser(foreName: exampleData[i], surName: exampleData[i+1], dateOfBirth: exampleData[i+2]);
}
我
如何能有效地重现此,如果exampleData是一个IEnumerable,而不是一个阵列?
How could I efficiently reproduce this if exampleData was an IEnumerable instead of an array?
推荐答案
这是有效的方法是用一个扩展方法:
An efficient approach would be with an extension method:
public static IEnumerable<IList<T>> ChunksOf<T>(this IEnumerable<T> sequence, int size)
{
List<T> chunk = new List<T>(size);
foreach (T element in sequence)
{
chunk.Add(element);
if (chunk.Count == size)
{
yield return chunk;
chunk = new List<T>(size);
}
}
}
您可以使用这样的:
foreach (IList<string> chunk in exampleData.ChunksOf(3))
{
CreateUser(foreName: chunk[0], surName: chunk[1], dateOfBirth: chunk[2]);
}
请注意,如果 sequence.Count()
不是尺寸
,然后<$ C $的整数倍C> ChunksOf 放弃最后的部分块。相反,如果你想返回部分块,你可以添加到末尾:如果(chunk.Count大于0)收益回报块;
Note that if sequence.Count()
is not an integer multiple of size
, then ChunksOf
discards the last partial chunk. If instead you wanted to return a partial chunk, you could add to the end: if (chunk.Count > 0) yield return chunk;
.
这篇关于.NET迭代通过在一个时间一个IEnumerable的几个要素的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!