开发者

Error when using LINQ with anonymous classes and implicitly typed arrays in ASP.NET WebPages

开发者 https://www.devze.com 2023-03-11 15:23 出处:网络
I am trying to mock up a page using WebMatrix using WebPages under the hood. I have assigned an implicitly typed array of anonymous objects to one of the PageData keys, but I get the following error w

I am trying to mock up a page using WebMatrix using WebPages under the hood. I have assigned an implicitly typed array of anonymous objects to one of the PageData keys, but I get the following error when I try to using LINQ methods on the collection:

CS1977: Cannot use a lambda expression as an argument to a dynamically dispatched operation without first casting it to a delegate or expression tree type

Here is some sample code:

@{
  PageData["Vals"] = new [] {
    new { ID=1, Quantity=5 },
    new { ID=2, Quantity=3 }
  };
  var sum = PageData["Vals"].Sum(x => x.Quantity);
}

If I first store the array in a regular开发者_StackOverflow中文版 object, I can use the LINQ methods on it just fine. It seems to have a problem when it comes out of PageData as a dynamic object - but I can't quite seem to figure out the secret sauce to coerce it back to the initial type.


The general solution to this problem is to explicitly cast it. i.e. Cast the expression PageData["Vals"] to an array of the type you expect. However, this cannot work with anonymous types because you don't have the handle to its type and therefore cannot cast it.

Once you've stored your new[] { ... } in the dynamically typed PageData, you've lost all compile-time reference to the anonymous type. Therefore, trying to use type-specific LINQ operators on it is a non-starter.

As I mentioned in the comments, the correct solution is to always use strongly-typed models. You should not be relying on anonymous types declared and defined within a view in order to mock up the page. Have the page depend on a real model and populate that model and feed it to the page.

0

精彩评论

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