将C#linq代码转换为VB。 [已编辑]

时间:2012-10-03 11:39:35

标签: c# vb.net linq entity-framework

我想将一些我的EntityFramework C#代码移植到VB.NET中。我正在尝试不同的在线代码转换器,但他们无法为我解决这个问题。

我有这两个功能。

public List<T> Find<T>(Func<T, bool> predicate) where T : class
    {
        var objectSet = db.CreateObjectSet<T>();
        return objectSet.Where<T>(predicate).ToList();
    }

    public void Delete<T>(Func<T, bool> predicate) where T : class
    {
        var objectSet = db.CreateObjectSet<T>();
        IEnumerable<T> records = from x in objectSet.Where<T>(predicate) select x;

        foreach (T record in records)
        {
            objectSet.DeleteObject(record);
        }
    }

现在转换器告诉我这个:

Public Function Find(Of T As Class)(predicate As Func(Of T, Boolean)) As List(Of T)
    Dim objectSet = db.CreateObjectSet(Of T)()
    Return objectSet.Where(Of T)(predicate).ToList()
End Function

Public Sub Delete(Of T As Class)(predicate As Func(Of T, Boolean))
    Dim objectSet = db.CreateObjectSet(Of T)()
    Dim records As IEnumerable(Of T) = From x In objectSet.Where(Of T)(predicate) Select x

    For Each record As T In records
        objectSet.DeleteObject(record)
    Next
End Sub

但我得到两个错误,objectSet.Where<T>(predicate)都是:

  

重载解析失败,因为没有可访问的“Where”接受此类型的参数。

1 个答案:

答案 0 :(得分:4)

只需从您对Where的调用中删除类型参数,无论如何都不必要。其次,决定一种风格:使用LINQ或函数,而不是两者。

即,

  • 写道:

    Dim records As IEnumerable(Of T) = From x In objectSet Where predicate(x) Select x
    

    ...但在VB中你可以不用Select x

    Dim records As IEnumerable(Of T) = From x In objectSet Where predicate(x)
    
  • 或写:

    Dim records As IEnumerable(Of T) = objectSet.Where(predicate)
    

Find相同。只需写下:

Return objectSet.Where(predicate).ToList()