Tell me more ×
Stack Overflow is a question and answer site for professional and enthusiast programmers. It's 100% free, no registration required.

I have a ASP.NET MVC4 Application. My view get a List from my controller. I want to select these list with lambda expression but I get the following error:

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

List<project.Models.LAYER> layers = new List<project.Models.LAYER>();
layers = @Model.layers.Select(x => x.KONT == "EUROPE");

@Model.layers is a List

NOW I TRIED THAT: BUT THE SAME ERROR:

@{
  List<project.Models.LAYER> layers = Model.layers.Where(x => x.KNOT == "EUROPE").ToList();
}
share|improve this question
Are you sure this code compiles? You don't need the @ sign here which would switch from HTML to a C# expression (and back at the end of the expresion). But your extract of the code is pure C# (no need to switch). Furthermore, why do you assign a new empty list to layers and the immediately assign it another value? – Codo 17 hours ago
What sort of list is Model.layers? Is it a List<project.Models.LAYER>? Probably not as the error message indicates there is a dynamic type involved somewhere. – Codo 16 hours ago

2 Answers

up vote 2 down vote accepted

It looks like you're doing this in your view, which violates the principles of separation of concerns. But this is how you would do it.

@
{
   var layers = Model.layers.Where(x => x.KONT == "EUROPE").ToList();
}

@foreach(var layer in layers)
{
  .....
}

A Better Way

What you should do however is create a method on your Model "GetLayersForLocation" Then your code would look like this:

In Your Model Class

public IEnumerable<Layer> GetLayersForLocation(string location)
{
    return this.layers.Where(x => x.Knot == location);
}

In Your View Code

@foreach(var layer in Model.GetLayersForLocation("EUROPE"))
{
  .....
}

The reason this is better is you can now unit test your code, before you wouldn't be able to because it's just part of your view, but now you can run automated tests to ensure that getting the proper layers is working.

share|improve this answer
  1. layers is a List, Model.layers.Select will return an IEnumerable.

  2. If you only want to return layer whose KONT == ‘EUROPE', you should use like following

    layers = @Model.layers.Where(x => x.KNOT == "EUROPE").ToList();

share|improve this answer
Thanks for your answer: I tried that now: @{ List<poettinger.Models.LAYER> layers = new List<project.Models.LAYER>(); layers = @Model.layers.Where(x => x.KNOT == "EUROPE").ToList(); } But there is still the same error. – user694501 17 hours ago

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.