开发者

Return IEnumerable<dynamic> from a method

开发者 https://www.devze.com 2023-03-13 11:06 出处:网络
How can I return IEnumerable from a method. public IEnumerable<dynamic> GetMenuItems() { dynamic menuItems = new[]

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 us开发者_StackOverflow社区e it in the View it does not recognize the Title property.

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


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.


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; 

   }
0

精彩评论

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

关注公众号