How to create LINQ Expression Tree to select an anonymous type

前端 未结 9 779
夕颜
夕颜 2020-11-22 12:12

I would like to generate the following select statement dynamically using expression trees:

var v = from c in Countries
        where c.City == \"London\"
           


        
9条回答
  •  予麋鹿
    予麋鹿 (楼主)
    2020-11-22 12:52

    This compiles, I dunno if it works however...

    myEnumerable.Select((p) => { return new { Name = p.Name, Description = p.Description }; });
    

    Assuming p is what your transforming, and the select statement is returning an anon type, using the function declaration of lambda's.

    Edit: I also don't know how you would generate this dynamically. But at least it shows you how to use the select lambda to return an anon type with multiple values

    Edit2:

    You would also have to bare in mind, that the c# compiler actually generates static classes of the anon type. So the anon type does actually have a type after compile time. So if your generating these queries at run time (which I assume you are) you may have to construct a type using the various reflection methods (I believe you can use them to make types on the fly) load the created types into execution context and use them in your generated output.

提交回复
热议问题