Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Lambda Expression for LINQ Select Items

I have this code

var list = _db.Projects.Where(item => item.Loc =="IN").Select(p => new {id=p.Id, title=p.Title,pc=p.PostalCode });

Project table having lot of columns, i need to query required columns dynamically and load from database, not all columns along with data.

Questions:

  1. how to write lambda expressions for linq select ?
  2. How to reduce data reads on database by selecting specific cols, entity framework ?
like image 903
Ramesh Bolla Avatar asked Mar 17 '26 04:03

Ramesh Bolla


1 Answers

Look at the expression the C# compiler generated and try to replicate what it does:

Expression<Func<Project, object>> lambda =
    (Project p) => (object)new {id=p.Id, title=p.Title,pc=p.PostalCode };

I hope this code compiles. If not, you'll surely be able to fix it. Afterwards, look at the contents of the lambda variable.

Note, that the cast to object is only there to make this compile. You don't need/want that is production.

like image 175
usr Avatar answered Mar 20 '26 02:03

usr