[英]Dynamic lambda expression for where clause
我有一個動態的對象列表,在其中使用lambda表達式where子句過濾項目。 例如,僅考慮它具有3個屬性,即foo,bar和baz
class item // let this be current class in dynamic item list
{
bool foo;
string bar;
string baz;
}
現在,如果要過濾foo為false的項目列表,可以使用以下表達式
var filtered = itemList.Where("!foo");
我什至可以按字符串值過濾列表為
var filtered = itemList.Where("bar==\"value\""); \\all items with bar = value
我要實際檢查的是列表中的項目是否具有特定的字符串值,而不是空白。 我嘗試了以下代碼
var filtered = itemList.Where("!String.IsNullOrWhiteSpace(baz)");
它拋出了一個錯誤
類型'System.Func`2 [DynamicType,System.Object]'的表達式不能用於方法'Boolean IsNullOrWhiteSpace(System.String)'的類型'System.String'的參數
雖然我通過以下查詢成功獲得了結果
var filtered = itemList.Where("baz!=null && baz!=\"\"");
我想確認是否可以在此查詢中使用String.IsNullOrWhiteSpace()
。
您可以將“!String.IsNullOrWhiteSpace(baz)”替換為“!(baz == null || baz.Trim()== string.Empty)”,它應該可以工作。
看一下System.Linq.Dynamic ,這里有一個很好的例子 。
您還需要確保List<T>
不是List<object>
,否則System.Linq.Dynamic將無法找到屬性。
這是您的示例的片段:
void Main()
{
var itemList = new List<dynamic>{ new {foo = true, bar = "a", baz = "b" }, new {foo = true, bar = (string)null, baz = "d" } };
var filtered = itemList.ToAnonymousList().Where("bar != null and bar !=\"\"");
filtered.Dump();
}
public static class EnumerableEx {
public static IList ToAnonymousList(this IEnumerable enumerable)
{
var enumerator = enumerable.GetEnumerator();
if (!enumerator.MoveNext())
throw new Exception("?? No elements??");
var value = enumerator.Current;
var returnList = (IList) typeof (List<>)
.MakeGenericType(value.GetType())
.GetConstructor(Type.EmptyTypes)
.Invoke(null);
returnList.Add(value);
while (enumerator.MoveNext())
returnList.Add(enumerator.Current);
return returnList;
}
}
我使用您的表情沒問題-效果很好。
我已經將它與針對EF存儲的對象和實體一起使用了。
類型'System.Func`2 [DynamicType,System.Object]'的表達式不能用於方法'Boolean IsNullOrWhiteSpace(System.String)'的類型'System.String'的參數
因此,看着錯誤,它說明了(移動順序):
返回一個Boolean
IsNullOrWhiteSpace
方法需要一個類型為System.String
的參數。 但是收到的是Expression of type System.Func``2[DynamicType,System.Object]'
看起來您可能已經引用了對象而不是字符串值進行比較。 但是,如果沒有正在使用的對象的示例代碼,以及是否正在使用對象,實體或LinQ to SQL(我沒有嘗試過),我們只能猜測您為表達式提供了什么。
最后,什么是
“動態項目列表”?
您使用的是Dynamic
還是正常的List<Item>
?
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.