开发者

Cast Linq IEnumerable to Class that inherits Ienumerable

开发者 https://www.devze.com 2022-12-13 08:37 出处:网络
I have a resultset class: Public Class AResultSet Implements IEnumerable(Of ConcreteResult) Private _list As List(Of ConcreteResult)

I have a resultset class:

Public Class AResultSet
    Implements IEnumerable(Of ConcreteResult)

    Private _list As List(Of ConcreteResult)

    Public Sub New()
        _list = New List(Of ConcreteResult)
    End Sub

    Public Function GetEnumerator() As System.Collections.Generic.IEnumerator(Of ConcreteResult) Implements System.Collections.Generic.IEnumerable(Of ConcreteResult).GetEnumerator
        Return _list.GetEnumerator
    End Function

    Public Function GetEnumerator1() As System.Collections.IEnumerator Implements System.Collections.IEnumerable.GetEnumerator
        Return _list.GetEnumerator
    End Function
End Class

and a linq query:

Dim res As AResultSet = (From pk In testPackages, _
         pp In pk.PackagePriceCollection _
          Select New ConcreteResult(pk, pp))

开发者_开发技巧But I get a cast error. So if I change the

Dim res As AResultSet 

To:

Dim res As IEnumerable(Of ConcreteResult)

It works. But I want to cast the linq query result to the type AResultSet, which is also an IEnumerable(Of ConrecteResult).

Or am I doing something wrong here?


The result of calling Select is not an AResultSet, which is why the cast will fail. Nothing in the query knows that you want to create a AResultSet. Just because the result and AResultSet both implement the same interface doesn't mean they're the same type.

You could create an instance of AResultSet from the results, however:

Dim query = (From pk In testPackages, _
     pp In pk.PackagePriceCollection _
     Select New ConcreteResult(pk, pp))
Dim res as AResultSet = new AResultSet(query.ToList)


While it's unclear to me why you might want to create a class to duplicate the functionality of List(Of T), what you are trying to do is not directly possible. You should either create an implicit (Widening) user defined cast operator in your class or create a constructor that takes an IEnumerable(Of ConcreteResult) and uses that to fill the private list field.

Public Class AResultSet
      Implements IEnumerable(Of ConcreteResult)
   Private list As List(Of ConcreteResult)
   Private Sub New(l As List(Of ConcreteResult))
      list = l
   End Sub
   Public Shared Widening Operator CType(seq As IEnumerable(Of ConcreteResult)) As AResultSet
      Return New AResultset(seq.ToList())
   End Sub
   ...
End Class 
0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号