2014-06-16 28 views
0

我想將運行時構建的表達式(CustomExpression)與普通的選擇函數結合起來。有沒有什麼辦法在C#中做到這一點,而無需手動構建整個表達式?LINQ select中的多個表達式

var dto = iqueryable.Select(d => new DTO() 
{ 
    X = d.X, 
    Y = d.Y, 
    Z = CustomExpression 
} 

哪裏CustomExpression是這樣的:

private Expression<Func<EntityTypeFromIQueryable, string>> CustomExpression() { 
    get { 
     // there is manually built expression like this: 
     return x => x.Blah 
    } 
} 
+0

你有沒有試過這段代碼?它工作嗎?或者您收到任何錯誤 –

+0

不,您無法編譯此代碼。不能隱式地將類型'System.Linq.Expressions.Expression >'轉換爲'字符串' –

+0

想象一下,「Z」屬性是類型字符串,但CustomExpression是表達式,在編譯返回字符串之後。 –

回答

2

您必須插入某種編譯佔位符(像一個擴展方法)首先進入你的表情。然後,在運行時,您可以使用表達式訪問者來修改表達式,以用實際的lambda表達式替換「佔位符」。由於您的實際表達式使用不同的參數dx),因此您必須將它們替換爲「原始」表達式的值。

事實上,我在this project內玩過這種場景,在那裏我試圖抽象這種表達管道。您的「合併」會再看看這樣的:

var dto = iqueryable.ToInjectable().Select(d => new DTO() 
{ 
    X = d.X, 
    Y = d.Y, 
    Z = d.CustomExpression() 
} 

public static class CustomExpressions 
{ 
    [InjectLambda] 
    public static string CustomExpression(this EntityTypeFromIQueryable value) 
    { 
     // this function is just a placeholder 
     // you can implement it for non LINQ use too... 
     throw new NotImplementedException(); 
    } 

    public static Expression<Func<EntityTypeFromIQueryable, string>> CustomExpression() 
    { 
     return x => x.Blah 
    } 
} 

呼叫ToInjectable()周圍產生原始可查詢一個輕量級的代理描述執行前修改的表達。屬性InjectLambda將「佔位符」標記爲「此處注入lambda」。按照慣例,由ToInjectable()返回的實際表達式被插入到期望的位置。

-1

您可以按以下方式做到這一點:

static void MultipleExpressionInSelectStatement() 
    { 
     List<person> p = new List<person>(); 
     p.Add(new person() { name = "AB", age = 18 }); 
     p.Add(new person() { name = "CD", age = 45 }); 
     var dto = p.Select(d => new person() 
     { 
      name=d.name, 
      age=p.Select(ListExtensions.CustomExpression()).ElementAt(0) 
     }); 
    } 

//customExpression 

public static class ListExtensions 
{ 


    public static Func<person, int> CustomExpression() 
    { 
     return x => x.age; 
    } 
} 

//Person Object 

public class person 
{ 
    public string name { get; set; } 
    public int age { get; set; } 
} 
+0

謝謝,但這是Func,而不是表達式 –