LINQ to Entities select columns with expression parameter

I can't wrap my head around how I can manage to select columns in a query by specifying an expression as a parameter.

Method A(IQueryable<Order> query)

      

Inside method A, I want to specify which columns to select, so I don't get all the columns right away, like this:

query.Select(x => new { x.OrderNumber, x.Payment, x.Customer })

      

It's easy if I specify it directly in method A, but I want to pass information using a parameter. I tried using an expression like this:

Expression<Func<Order, dynamic>> columns

      

But I can't get it to work as I can only specify one column where I am calling method A, for example:

MethodA(query, (x) => x.OrderNumber);

      

How can I specify more than one property?

+3


source to share


2 answers


I found a solution. I just needed to specify an anonymous type:

MethodA(query, order => new { order.OrderNumber, order.Payment })

      



Now I can pass my Select expression from other methods.

+2


source


If you just want to pass the column names, why not pass the strings as an array?



void MethodA(params string[] columns)

0


source







All Articles