Reputation: 24699
Is this the most straight forward way to return a typed collection?
Sorry for the repeated question. Now I am looking for a better way...
Here's the key line of code which returns a implicit type of IEnumerable that used to manually loop through to manually recreated a TYPED collection. Is there any native LINQ way to return a typed sorted collection without this recreating of the collection?
Dim Sorted As ErrorProviderMessageCollection = New ErrorProviderMessageCollection(From item In MyCollection Order By item.Control.TabIndex)
Public Class ErrorProviderMessageCollection
Inherits System.Collections.ObjectModel.Collection(Of ErrorProviderMessage)
Public Sub New()
End Sub
Public Sub New(ByVal source As IEnumerable(Of ErrorProviderMessage))
Dim orderedCollection = New ErrorProviderMessageCollection()
For Each Item As ErrorProviderMessage In source
Me.Add(Item)
Next
End Sub
End Class
Public Class ErrorProviderMessage
Public Sub New(ByVal message As String, ByVal control As Control)
_Message = message
_Control = control
End Sub
Public ReadOnly Property Message() As String
Public ReadOnly Property Control() As Control
End Class
Upvotes: 0
Views: 251
Reputation: 700432
No, there is no LINQ way of doing that, as the Collection<T>
class is not one of the collection types that it uses.
You can turn the IEnumerable<T>
into a List<T>
, which implements IList<T>
, and there is a constructor for Collection<T>
that takes an IList<T>
:
Dim Sorted As Collection<ErrorProviderMessage> = _
New Collection<ErrorProviderMessage>( _
(From item In MyCollection Order By item.Control.TabIndex).ToList() _
)
Upvotes: 1
Reputation: 36573
The key point to remember about LINQ is that it's based on deferred execution.
If you do
Dim y = col.Where(Function(i) i.SomeProp = True)
You AREN'T actually creating a new collection. LINQ is creating an enumerator that executes on each item in col on demand.
So, the short answer is, no, LINQ yields items in an enumerable, it doesn't return new collections (with the exception of methods like ToList or ToArray or ToDictionary which force enumeration).
If you want a new typed collection, you need to force enumeration:
Dim col2 = New ErrorProviderMessageCollection(col.Where(Function(i) i.SomeProp = True))
Upvotes: 2