如何在VB.NET集合类中实现LINQ功能



我有一个收集类,它是

的包装器
List(Of MyClass)

和收集类实施诸如添加,计数等的事物

Private lst As List(Of MyClass)
Public Function Count() As Long
    Return lst.Count
End Function

我想添加在集合类上进行LINQ查询的功能。因此,客户可以做这样的事情:

dim c as New MyCollectionClass
c.Add(New MyClass With {.Name = "XXX"})
c.Add(New MyClass With {.Name = "XXX"})
c.Add(New MyClass With {.Name = "YYYY"})
Dim nc As MyCollectionClass = c.GroupBy(function(x) x.Name)

如何实现GroupBy函数和所有其他LINQ函数(选择,过滤,独特,订购等(?我已经在课堂上实现了可视化。

我对如何声明它及其参数和实现等感到困惑。我尝试了一些

之类的事情
Public Function GroupBy(f As Func(Of MyClass)) As IEnumerable
    Return lst.GroupBy(Function(x As MyClass) f(x))
End Function

但这只是语法错误,我现在只是卡住了:)谢谢

fwiw这是我为iQueryable所做的:

Implements IEnumerable, IQueryable
Private lst As New List(Of MyClass)
Public ReadOnly Property Expression As Expression Implements IQueryable.Expression
    Get
        Return lst.AsQueryable.Expression
    End Get
End Property
Public ReadOnly Property ElementType As Type Implements IQueryable.ElementType
    Get
        Return lst.AsQueryable.ElementType
    End Get
End Property
Public ReadOnly Property Provider As IQueryProvider Implements IQueryable.Provider
    Get
        Return lst.AsQueryable.Provider
    End Get
End Property

您无需重新实现Linq扩展(SelectGroupBy等(。您只需要实现IEnumerable(Of MyClass),然后标准Linq扩展就可以自动使用您的课程。

IEnumerable(Of ...)实现的示例:

Public Class MyCollection
    Implements IEnumerable(Of MyClass1)

    Private lst As New List(Of MyClass1)
    Public Function GetEnumerator() As IEnumerator(Of MyClass1) Implements IEnumerable(Of MyClass1).GetEnumerator
        Return lst.GetEnumerator()
    End Function
    Private Function IEnumerable_GetEnumerator() As IEnumerator Implements IEnumerable.GetEnumerator
        Return DirectCast(lst, IEnumerable).GetEnumerator()
    End Function
End Class

和用法:

Dim collection = New MyCollection
...
Dim count = collection.Count()

最新更新