How to create LINQ Expression Tree to select an anonymous type

前端 未结 9 770
夕颜
夕颜 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:39

    I don't believe that you will be able to achieve this. Although when you do select new { c.Name, c.Population } it seems like you're not creating a class you actually are. If you have a look at the compiled output in Reflector or the raw IL you will be able to see this.

    You'll have a class which would look something like this:

    [CompilerGenerated]
    private class <>c__Class {
      public string Name { get; set; }
      public int Population { get; set; }
    }
    

    (Ok, I cleaned it up a touch, since a property is really just a get_Name() and set_Name(name) method set anyway)

    What you're trying to do is proper dynamic class creation, something which wont be available until .NET 4.0 comes out (and even then I'm not really sure if it'll be able to achieve what you want).

    You're best solution would be to define the different anonymous classes and then have some kind of logical check to determine which one to create, and to create it you can use the object System.Linq.Expressions.NewExpression.

    But, it may be (in theory at least) possible to do it, if you're getting really hard-core about the underlying LINQ provider. If you are writing your own LINQ provider you can detect if the currently-parsed expression is a Select, then you determine the CompilerGenerated class, reflect for its constructor and create.

    Defiantly not a simple task, but it would be how LINQ to SQL, LINQ to XML, etc all do it.

提交回复
热议问题