Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do we retrieve the first item of a WhereSelectListIterator?

How do we retrieve the first item of a WhereSelectListIterator? Usually, I use a foreach loop to iterate. Is there a way to call the equivalent of myResult[0] or myResult.FirstOrDefault(). Both throw an error. myResult.ToList() doesn't work either. I am beginning to think that the only thing we can do with a WhereSelectListIterator is iterate with foreach.

Here is the scenario: I have created an Orchard Query with a Shape layout. The Shape 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>

Specifically, contentItems was of type

System.Linq.Enumerable.WhereSelectListIterator<
    Orchard.Projections.Descriptors.Layout.LayoutComponentResult,
    Orchard.ContentManagement.ContentItem>

Please let me know if you need more details about why I might want to retrieve the first item.

like image 456
Shaun Luttin Avatar asked Mar 19 '23 19:03

Shaun Luttin


1 Answers

The issue is that you have a dynamic object and the LINQ methods (ToList, FirstOrDefault) you are trying to use are extension methods on IEnumerable<T>. The DLR does not have enough information at runtime to resolve extension methods when they are invoked like instance methods. Since extension methods are really just static methods with special attributes attached, you can invoke them in the static style as well:

var contentItems = Model.ContentItems;
dynamic firstItem = System.Linq.Enumerable.FirstOrDefault(contentItems);
like image 65
Mike Zboray Avatar answered Mar 21 '23 09:03

Mike Zboray