Build LINQ Select conditionally similar of using PredicateBuilder for Where clause [duplicate]

StackOverflow https://stackoverflow.com/questions/19691496

  •  02-07-2022
  •  | 
  •  

Question

I'm working with dynamic queries using LINQ on Entity Framework. To query some tables by user input filters, we are using PredicateBuilder to create conditional WHERE sections. That works really great, but the number of columns returned are fixed.

Now, if we need the user to select which columns he needs in their report, besides their filters, we are in trouble, as we don't know how to do dynamic myQuery.Select( x => new { ... }) as we do for Where clause.

How can we achieve something like this?

Was it helpful?

Solution

A bit of searching reveals that this is tricky. Anonymous types are created at compile time, so it is not easy to create one dynamically. This answer contains a solution using Reflection.emit.

If possible, I would recommend just returning something like a IDictionary<,> instead.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top