Lambda Expression for LINQ Select Items

2019-05-14 21:01发布

问题:

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 ?

回答1:

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.