2

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)'.

3 Answers 3

4

Sounds like you want Enumerable.OfType():

Dim peopleList as List(Of Person) = objectsList.OfType(Of Person)().ToList()
Sign up to request clarification or add additional context in comments.

2 Comments

in fact, you obtain an IEnumerable, not a List(Of), but pretty cool enough! ) Thank you )
@serhio the ToList() does that last step
1

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();

Comments

0

In C# it would be

ObjectList.OfType<Person>()

VB .Net would be something similar

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.