johndoe
johndoe

Reputation: 25

Return IEnumerable<dynamic> from a method

How can I return IEnumerable from a method.

 public IEnumerable<dynamic> GetMenuItems()
        {

            dynamic menuItems = new[]
                                    {
                                         new { Title="Home" },
                                    new { Title = "Categories"} 
                                    };

            return menuItems; 

        }

The above code returns IEnumerable but when I use it in the View it does not recognize the Title property.

@foreach(var item in @Model) 
{  
   <span>item.Title</span>
}  

Upvotes: 0

Views: 2945

Answers (2)

jbtule
jbtule

Reputation: 31799

Anonymous types are marked internal, so you can't access them from a different assembly. You can use an ExpandoObject instead although the default creation syntax doesn't work inline which can be annoying. However, the opensource framework impromptu-interface has a syntax for creating it inline.

using ImpromptuInterface.Dynamic;
using System.Dynamic;
...
public IEnumerable<dynamic> GetMenuItems()
   {
       var @new = Builder.New<ExpandoObject>();

       dynamic menuItems = new[]{
                   @new.Object(Title:"Home"),
                   @new.Object(Title:"Categories")
                };

       return menuItems; 

   }

Upvotes: 0

Anthony Pegram
Anthony Pegram

Reputation: 126804

Don't do this..

If you need to use the result of an anonymous type outside of the method that creates it, it is time to define a concrete type.

class Foo 
{
    public string Bar { get; set; }
}

Short of doing that, you can return a sequence of Tuple<> objects.

Anonymous types are nice when you're doing some processing inside a method, you need a projection of data that doesn't conform to your existing object graph, and you don't need to expose such a projection to the outside world. Once you start passing that projection around, go ahead and take the extra time to define a proper type and enjoy its benefits. Future You will thank you.

Upvotes: 9

Related Questions