gpt4 book ai didi

vb.net - 有效地将列表划分为固定大小的 block

转载 作者:塔克拉玛干 更新时间:2023-11-03 04:23:58 25 4
gpt4 key购买 nike

我真的很喜欢 algorithm如下所示,用于将列表拆分为固定大小的子列表。它可能不是有效的算法(编辑:根本)

我想要在可读性、优雅和性能之间取得良好平衡的东西。问题是,我在 C# 中找到的大多数算法都需要 yield 关键字,如果您在 Visual Studio 2010 中使用 .NET 3.5,则该关键字不可用 ;)

public IEnumerable<IEnumerable<T>> Partition<T>(IEnumerable<T> source, int size)
{
if (source == null)
throw new ArgumentNullException("list");

if (size < 1)
throw new ArgumentOutOfRangeException("size");

int index = 1;
IEnumerable<T> partition = source.Take(size).AsEnumerable();

while (partition.Any())
{
yield return partition;
partition = source.Skip(index++ * size).Take(size).AsEnumerable();
}
}

我尝试在 VB 中重写它,但不得不使用第二个列表来收集结果,这最终比上面的实现花费了更多的时间。

我正在寻找我可以在 VB.NET 中使用的另一种算法,但大多数结果都遇到了基本上必须将所有内容加载到内存中而不是动态生成结果的能力的问题 a la python 中的生成器。这不是一个大问题,但不如 yield return 理想。

在 VB.NET 中是否有一个好的、推荐的算法来执行此操作?我是否必须创建一些实现 IEnumerator 的东西才能按需生成结果?

最佳答案

这可能是一种变通方法。将子例程设为 Sub 并传入目标列表。现在您可以直接将子列表添加到其中,而无需先创建整个中间对象。

Dim testlist As New List(Of List(Of Integer))
Partition(Of Integer)({1, 2, 3, 4, 5, 6, 7, 8, 9, 1, 2, 3, 4, 5, 6, 7, 8, 9, 0}, 4, testlist)

Public Sub Partition(Of T)(source As IEnumerable(Of T), size As Integer, ByRef input As List(Of List(Of T)))
If source Is Nothing Then
Throw New ArgumentNullException("list")
End If
If size < 1 Then
Throw New ArgumentOutOfRangeException("size")
End If
For i = 0 To source.Count - 1 Step size
input.Add(source.Skip(i).Take(size).ToList())
Next
End Sub

关于vb.net - 有效地将列表划分为固定大小的 block ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20556678/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com