Reputation: 28586
I have
Dim objectsList as List(Of Object) = GetAllObjects()
' Filter from Objects just Persons '
Dim peopleList as List(Of Person) = ???
What is the most efficient and effective LINQ expression to do it?
EDIT
1 Dim selectedObjects As List(Of Object) = GetAllObjects()
2 Dim selectedPeople As IEnumerable(Of Person)= selectedObjects.OfType(Of Person)
3 Dim people As List(Of Person) = selectedPeople.ToList()
Error on 3:
Value of type 'System.Collections.Generic.List(Of System.Collections.Generic.IEnumerable(Of Person))' cannot be converted to 'System.Collections.Generic.List(Of Person)'.
Upvotes: 2
Views: 515
Reputation: 1063068
The most effecient approach is to filter at the point of origin (for example, at the point of database query, for example), not once we have the objects in memory, but:
Dim peopleList as List(Of Person) = objectsList.OfType(Of Person)().ToList()
or in C# (note this is identical once compiled):
var peopleList = objectsList.OfType<Person>().ToList();
Upvotes: 1
Reputation: 2595
In C# it would be
ObjectList.OfType<Person>()
VB .Net would be something similar
Upvotes: 0
Reputation: 1501163
Sounds like you want Enumerable.OfType()
:
Dim peopleList as List(Of Person) = objectsList.OfType(Of Person)().ToList()
Upvotes: 4