我正在尝试将以下算法从C#转换为VB.NET,而我所拥有的VB.NET并没有产生与我的C#算法相同的结果,有人可以告诉我在转换中我出错了吗?
public static IEnumerable<T[]> Combinations<T>(this IEnumerable<T> elements, int k)
{
List<T[]> result = new List<T[]>();
// single combination
if (k == 0)
{
result.Add(new T[0]);
}
else
{
int current = 1;
foreach (T element in elements)
{
//combine each element with k-1 combinations of subsequent elements
result.AddRange(elements
.Skip(current++)
.Combinations(k - 1)
.Select(combination => (new T[] { element }).Concat(combination).ToArray())
);
}
}
return result;
}
这是我在VB.NET中得到的:
<Extension()>
Public Function Combinations(Of T)(ByRef elements As IEnumerable(Of T), ByVal k As Integer) As IEnumerable(Of T())
Dim result As New List(Of T())()
'single combination'
If k = 0 Then
result.Add(New T(-1) {})
Else
Dim current As Integer = 0
For Each element As T In elements
'combine each element with k - 1 combinations of subsequent elements'
Dim local As T = element
result.AddRange(elements.Skip(current = current + 1).Combinations(k - 1).Select(Function(combs) (New T() {local}).Concat(combs).ToArray()))
Next
End If
Return result
End Function
有些事情是错的,但我不确定是什么,我猜这个问题是在lambda的某个地方.
任何人都可以指出我的转换错误吗?
最佳答案 使用代码转换器……
<System.Runtime.CompilerServices.Extension> _
Public Shared Function Combinations(Of T)(elements As IEnumerable(Of T), k As Integer) As IEnumerable(Of T())
Dim result As New List(Of T())()
' single combination
If k = 0 Then
result.Add(New T(-1) {})
Else
Dim current As Integer = 1
For Each element As T In elements
'combine each element with k-1 combinations of subsequent elements
result.AddRange(elements.Skip(System.Math.Max(System.Threading.Interlocked.Increment(current),current - 1)).Combinations(k - 1).[Select](Function(combination) (New T() {element}).Concat(combination).ToArray()))
Next
End If
Return result
End Function