0

I have a requirement to pass an IEnumerable<Object> to an MVC view and have the view cast this to a strongly typed object and display it accordingly.

This appears to be having a performance impact vs. passing it down as a IEnumerable of MyCustomObject.

foreach (var item in Model.Items)
{
    var current = (MyCustomObject) item;
    <p>@current.Submitted</p>
}

My questions are

  1. Should I cast the entire IEnumerable of Objects to IEnumerable of MyCustomObject?
  2. How can I improve the performance of this operation?
  3. If this is not good practice, what's the best way to pass a "variable" type for my Items collection, which could be a collection of any type of custom object?

Use a List pass this to the model, then it is strongly defined

Controller

public ActionResult Index(){

MyModel model = new MyModel();
model.list = //get list from source

return View(model);

}

Model

public List<MyCustomObject> list {get; set;}
4

2 回答 2

2

Initially, you could use Cast on the entire collection:

foreach (var item in Model.Items.Cast<MyCustomObject>()){}

If your types will all inherit from a base type, say MyCustomObject, then your model should specify this, e.g.

public class MyViewModel<T> where T : MyCustomObject, new() 
{
    public IEnumerable<T> Items { get; set; }
}

You would need to ensure that any types you wished to add to your items collection inherited from the base MyCustomObject type

于 2012-11-30T12:52:24.337 回答
2

使用 List 将其传递给模型,然后对其进行强定义

控制器

public ActionResult Index(){

MyModel model = new MyModel();
model.list = //get list from source

return View(model);

}

模型

public List<MyCustomObject> list {get; set;}
于 2012-11-30T12:45:27.060 回答