开发者

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


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.


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)
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜