[英]Add Contains to existing Func<T, object> property
我正在嘗試為現有的Func屬性列表創建Contains子句,但是我不知道如何將其附加到先前傳遞的屬性列表中。
public static List<Func<T, bool>> GetPropertyWhereClauses<T>(List<Func<T, object>> properties, string queryPhrase)
{
var whereClauses = new List<Func<T, bool>>();
foreach (var property in properties)
{
/// how to add Contains to existing property Func<T, object> ?
whereClauses.Add(property.Contains(queryPhrase));
}
return whereClauses;
}
如何添加呢? 我嘗試使用一些Expression.Call,但它沒有將Func作為參數。
如果僅要將每個Func<T, object>
轉換為Func<T, bool>
如果第一個轉換為string的func返回對象包含queryPhrase,則可以執行以下操作:
public static List<Func<T, bool>> GetPropertyWhereClauses<T>(List<Func<T, object>> funcs, string queryPhrase)
{
var whereClauses = new List<Func<T, bool>>();
foreach (var func in funcs)
{
whereClauses.Add(o => func(o).ToString().Contains(queryPhrase));
}
return whereClauses;
}
或更適合LINQ:
public static List<Func<T, bool>> GetPropertyWhereClauses<T>(List<Func<T, object>> funcs, string queryPhrase)
{
return funcs.Select(func => new Func<T, bool>(o => func(o).ToString().Contains(queryPhrase)).ToList();
}
如果reutrn對象實際上是列表而不是字符串,則可以通過類似的方式檢查queryPhrase是否是列表的一部分:
public static List<Func<T, bool>> GetPropertyWhereClauses<T>(List<Func<T, object>> funcs, string queryPhrase)
{
return funcs.Select(func => new Func<T, bool>(o => ((List<string>)func(o)).Contains(queryPhrase)).ToList();
}
如果您可以將func返回tpye變成一個對象,這不是最好的主意,則可以將其更改為期望的真實類型,這樣可以節省所有多余的轉換。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.