2017-10-16 118 views
0

動態C#表達我有以下對象結構,從給定的列表中選擇,包含給定值

public class Client 
{ 
    public Client() 
    { 
     Identifiers = new List<ExternalIdentifier>(); 
    } 

    public Guid? PatientId { get; set; } 
    . 
    . 

    public IList<ExternalIdentifier> Identifiers { get; set; } 
} 

我想建立以下內容的動態表達,

Clients.Where(s=>s.Identifiers.Select(a=>a.Value).ToList().Contains("d"));

這是我到目前爲止

public Expression GeneratExp(string consVal) 
{ 
    //TODO be removed .Where(s=>s.Identifiers.Select(a=>a.Value).ToList().Contains("d")); 

    ParameterExpression externalId = Expression.Parameter(typeof(ExternalIdentifier), "id"); 
    Expression idProperty = Expression.PropertyOrField(externalId, "Value"); 

    var valueSelector = Expression.Lambda<Func<ExternalIdentifier, string>>(idProperty, new ParameterExpression[] { externalId }); 

    ParameterExpression client = Expression.Parameter(typeof(Models.Entities.Client), "s"); 
    Expression id = Expression.PropertyOrField(client, "Identifiers"); 

    var selM = typeof(Enumerable).GetMethods().First(x => x.Name == "Select").MakeGenericMethod(typeof(ExternalIdentifier), typeof(string)); 
    var selExpression = Expression.Call(null, selM, id, valueSelector); 

    var toli = typeof(Enumerable).GetMethods().First(x => x.Name == "ToList").MakeGenericMethod(typeof(string)); 
    var toliexp = Expression.Call(null, toli, selExpression); 

    var cont = typeof(Enumerable).GetMethods().First(x => x.Name == "Contains").MakeGenericMethod(typeof(string)); 
    var contexp = Expression.Call(null, cont, toliexp, Expression.Constant("d")); 

    var retcontexp = Expression.Lambda<Func<Models.Entities.Client, bool>>(contexp, Expression.Parameter(typeof(Models.Entities.Client), "s")); 

    return retcontexp; 
} 

when我運行單元測試它建立了以下表達式 s.Identifiers.Select(a => a.Value).ToList()。Contains(「d」)

但自「s」i沒有定義,任何幫助建立以下非常讚賞。

S => s.Identifiers.Select(A => a.value中).ToList()。包含( 「d」)是非常讚賞

預先感謝。

回答

0

你非常非常接近達到理想的效果。您只需使用相同的​​您的Expression.Lambda<TDelegate>工廠方法的實例參數,您在定義表達式正文時使用該方法。前return改變你的方法的最後一行:

var retcontexp = Expression.Lambda<Func<Client, bool>>(contexp, client); 

...所得拉姆達將是有效的,你就可以編譯。

+0

工作就像一個魅力感謝堆! –

相關問題