How do I get the first element of the WhereSelectListIterator object?
How do I get the first item WhereSelectListIterator
? I usually use a loop foreach
to iterate. Is there a way to call the equivalent myResult[0]
or myResult.FirstOrDefault()
. Both throw an error. myResult.ToList()
doesn't work either. I'm starting to think that the only thing we can do with WhereSelectListIterator
is iterate with foreach
.
Here's the scenario: I created an Orchard Query with a Shape layout. The form template contains the following code:
@{
// content items is of type WhereSelectListIterator<T,T>
var contentItems = Model.ContentItems;
dynamic firstItem = null;
// {"Cannot apply indexing with [] to an expression of type 'object'"}
//// firstItem = contentItems[0];
// {"'object' does not contain a definition for 'ToList'"}
// var items = contentItems.ToList();
// get the title of the first content item
// this is what DOES work
foreach (var contentItem in contentItems)
{
firstItem = contentItem;
break;
}
}
<h2>@(firstItem != null ? firstItem.TitlePart.Title : "Got Nothing")</h2>
In particular, it contentItems
had the type
System.Linq.Enumerable.WhereSelectListIterator<
Orchard.Projections.Descriptors.Layout.LayoutComponentResult,
Orchard.ContentManagement.ContentItem>
Please let me know if you need more information on why I might get the first item.
source to share
The problem is that you have a dynamic object and the LINQ methods (ToList, FirstOrDefault) that you are trying to use are extension methods on IEnumerable<T>
. The DLR does not have enough run-time information to resolve extension methods when called like instance methods. Since extension methods are really just static methods with special attributes, you can call them in a static style as well:
var contentItems = Model.ContentItems;
dynamic firstItem = System.Linq.Enumerable.FirstOrDefault(contentItems);
source to share