将OrderBy谓词中的Lambda表达式从C#转换为VB.net

时间:2012-04-24 09:41:05

标签: c# vb.net predicate

我有以下内容按工作职位对实体进行排序。所需的顺序在另一个数组中定义。在C#中,此代码有效:

IEnumerable<CreditObject> query = credits.OrderBy(x =>
{
    for (int i = 0; i < list.Length; i++)
    {
        if (x.Job == list[i])
            return i;
    }
    throw new NotImplementedException("Job not within List");
});

但是我必须将其转换为VB.net。我读过等价的内容如下:

Dim query As IEnumerable(Of CreditObject) = credits.OrderBy(Function(x) 

    For j As Integer = 0 To templ.Length - 1
        If x.Job = templ(j) Then
            Return j
        End If
    Next

End Function)

这不编译,在Function(x)之后立即给我“表达期望”。我做错了什么?

1 个答案:

答案 0 :(得分:4)

首先,您将其变为真正的方法:

public int GetCreditObjectPosition(CreditObject x, List<int> list) {
    for (int i = 0; i < list.Length; i++) {
        if (x.Job == list[i]) {
            return i;
        }
    }
    throw new NotImplementedException("Job not within List");
}

然后,你只需说:

IEnumerable<CreditObject> query =
    credits.OrderBy(x => GetCreditObjectPosition(x, list));

这很容易转换为VB。

接下来,您重写GetCreditObjectPosition以获得巨大的性能改进:

public int GetCreditObjectPosition(CreditObject x, List<int> list) {
    var jobDictionary = 
        list.Select((job, index) => new { Job = job, Index = Index } )
            .ToDictionary(item => item.Job, item => item.Index);
    int position;
    if(!jobDictionary.TryGetValue(x.Job, out position)) {
        throw new Exception("Job not within List");
    }
    return position;
}