簡體   English   中英

如何編寫對屬性方法進行過濾的LINQ表達式樹?

[英]How do I write a LINQ Expression Tree that filters on a method of a property?

所以我有一個帶有屬性的對象集合:

ParentObject parentObj
{
    string SomeProperty1
    string SomeProperty2
}

在查詢這些屬性之前,需要將它們設置為ToLower()和Trim()。 我了解我可以做到:

Expression.Call(pe, typeof(string).GetMethod("Trim", Type.EmptyTypes)); // Or ToLower

Expression.Property(pe, typeof(string).GetProperty("SomeProperty1"));

但是,如何將它們結合起來?

我需要的東西相當於

from query in parentObjCollection
where query.SomeProperty1.Trim() == "asdf"
select query

有什么想法嗎?

Expression.Property本身會返回一個表達式,您可以將其用作調用的第一個參數(完整示例):

var parent = new ParentObject{ SomeProperty1 = "    test" };
var pe = Expression.Constant(parent);
var property = Expression.Property(pe, typeof(ParentObject).GetProperty("SomeProperty1"));
var call = Expression.Call(property, typeof(string).GetMethod("Trim", Type.EmptyTypes));

var result = Expression.Lambda(call).Compile().DynamicInvoke();

Console.WriteLine(result); // -> "test"

請注意,我必須修改您的Expression.Property調用。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM