微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

将算法从C#转换为VB.NET失败

我正在尝试将以下算法从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

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 [email protected] 举报,一经查实,本站将立刻删除。

相关推荐