我有以下按照实体的职位对实体进行排序的方法。在另一个数组中定义的所需顺序。在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)
之后立即给出“期望的表达式”。我究竟做错了什么? 最佳答案
首先,将其变成一种真实的方法:
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;
}
关于c# - 将OrderBy谓词中的Lambda表达式从C#转换为VB.net,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/10295379/