0

If I have a collection of Expression<Func<TSource, object>> Select expressions

like e => e.Id and e => e.Name

How can I combine them to create one expresion like:

Select{ e => new {e => e.Id, e => e.Name}}

Edited


I have method helper to get lambda select expression from list of field or properties

public static ICollection<Expression<Func<IQueryable<TSource>, object>>> BuildSelectExpressionCollection<TSource>(this IEnumerable<string> selects)

It simply use property like "Id" and convert to some lambda expression

But I want to cope with this collection of expressions

To execute Select with linq query

But if I use it in cycle

It can build many Select expression like:

someQueryableCollection.Select(e=>e.Id).Selct(e=>e.Name) and so on

If it possible to combine then in one Select query?


Edited 2


1.I accept some select query from url ($select=Name,Id)

2.Then I have method to get all properties from select query to list (List list = this fiels that I get (Name, Id))

3.The problem is that I have url query to DTO model but I want to convert it to entity Model filds and than execute query to return only Name and Id

What I have done so far:

  • get list of lambda expression to property fields like e=>e.Id and so on
  • than I use expression visitor to convert lambda expressions acording to fields of entity model
  • but this is a problem that compiler can resolve type of lambda expression at runtime and how to combine lambdas in one select query?
FairyFox5700
  • 11
  • 1
  • 3
  • 4
    If you're trying to select an anonymous type, just do: `Select(e => new {e.Id, e.Name})`. If you're trying to do something else, please [edit](https://stackoverflow.com/posts/62199142/edit) your question with clarification. – Rufus L Jun 04 '20 at 16:07
  • 3
    this isn't as simple as you'd want, as this would require generating a type *at runtime*, which is *very* hard; anonymous types are not something you can project to trivially. Would projecting to a value-tuple be viable? – Marc Gravell Jun 04 '20 at 16:18
  • Agree with Marc - usually I just go `Select(e => (e.Id, e.Name))`. – Alexander Høst Jun 04 '20 at 17:00
  • _Consider_: What type would you expect to be returned from the created lambda? How would the compiler know about that? (Remember, anonymous types are compile time static types, they are not created at runtime - they just don't require the user to code them.) PS @MarcGravell I wouldn't say _very hard_, just typically not useful. – NetMage Jun 04 '20 at 19:49
  • Your questions is answered [here](https://stackoverflow.com/questions/606104/how-to-create-linq-expression-tree-to-select-an-anonymous-type/28140345). HTH. – Thimmu Lanka Jun 07 '20 at 04:47

0 Answers0