Chad
Chad

Reputation: 24699

LINQ - Select a *TYPED* item in a collection

Can I use LINQ to return an item in a collection that is the same TYPE as the items in the collection? I am a LINQ Noob trying to avoid looping.

    Dim mostRecentlyCreatedQuestionnaire As ParentQuestionnaireItem = 

CType((From P In questionnaireCollection Order By P.Metadata.CreateDate Descending).Take(1), ParentQuestionnaireItem)

I get an "unable to CAST" error when I include the CTYPE function. I kind of expected that error, but I imagine that if I coul dnot do this, LINQ's usefulness would be diminished and therefore assume that there must be a way...

Upvotes: 1

Views: 549

Answers (2)

msarchet
msarchet

Reputation: 15242

The reason that Take(1) doesn't work is that Take(1) returns a IEnunmerable(Of TSource) or IQueryable(Of TSource) depending on the query, why First return an Object of Type TSource

Dim mostRecentlyCreatedQuestionnaire As ParentQuestionnaireItem = 
DirectCast((From P In questionnaireCollection Order By P.Metadata.CreateDate Descending).First, ParentQuestionnaireItem)

Upvotes: 1

Daniel Hilgarth
Daniel Hilgarth

Reputation: 174329

Just do this:

Dim mostRecentlyCreatedQuestionnaire As ParentQuestionnaireItem = 

(From P In questionnaireCollection Order By P.Metadata.CreateDate Descending).FirstOrDefault()

The problem with your approach is, that Take returns an enumerable, even if you just take 1.

My answer assumes that questionnaireCollection is strong typed.

Upvotes: 3

Related Questions