serhio
serhio

Reputation: 28586

LINQ sample: select typed objects from a list

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

Answers (3)

Marc Gravell
Marc Gravell

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

Viv
Viv

Reputation: 2595

In C# it would be

ObjectList.OfType<Person>()

VB .Net would be something similar

Upvotes: 0

Jon Skeet
Jon Skeet

Reputation: 1501163

Sounds like you want Enumerable.OfType():

Dim peopleList as List(Of Person) = objectsList.OfType(Of Person)().ToList()

Upvotes: 4

Related Questions