我有一个很大的 C# 哈希集,但无法一次处理全部内容。我需要提取具有给定大小的 block 。我知道我可以迭代哈希并将每个元素复制到可以稍后处理的数组/列表中,但是有没有更快/更优雅的方法来做到这一点?像单行一样的东西?
public static IEnumerable<T[]> Slice<T>(this HashSet<T> h, int size)
{
if (0 >= size)
{
throw new Exception("0 or negative slice sizes are not accepted!");
}
if (null == h || 0 == h.Count)
{
yield return new T[0];
yield break;
}
if (size >= h.Count)
{
yield return h.ToArray();
yield break;
}
List<T> to_ret = new List<T>(size);
foreach (T elem in h)
{
if (size == to_ret.Count)
{
yield return to_ret.ToArray();
to_ret.Clear();
}
to_ret.Add(elem);
}
if (0 < to_ret.Count)
{
yield return to_ret.ToArray();
to_ret.Clear();
}
}
我就是这样做的...我在想还有比这更优雅的方法。 :(
最佳答案
没有任何内置内容。
但是,如果您使用 MoreLinq库(这是一个有用的东西),那么它有一个 Batch执行您想要的操作。
int batchSize = 1024;
foreach (var batch in myHashSet.Batch(batchSize))
{
foreach (var item in batch)
{
...
}
}
关于c# - 对 C# 哈希集进行切片,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21575053/