我想用LinqPad建立一個基本的動態Linq查詢。我的方法要求用戶選擇1 - 3選項,然後根據其輸入動態構建查詢。動態Linq查詢不按預期工作 - 我做錯了什麼?
public void FilteredPropertySearch()
{
bool addAnotherOption = true;
int option;
Dictionary<int, bool> parameters = new Dictionary<int, bool>();
var predicate = PredicateBuilder.False<ResidentialProperty>();
Console.WriteLine("Follow instructions to filter property search results");
do
{
// get user input
option = int.Parse(Console.ReadLine());
switch(option)
{
case 1:
parameters.Add(1, true);
break;
// more cases - when case 0 addAnotherOption = false, loop ends
default:
Console.WriteLine("That was not a valid option");
break;
}
}while(addAnotherOption == true);
foreach(KeyValuePair<int, bool> p in parameters)
{
if(p.Key == 1 && p.Value == true)
predicate = predicate.Or (c => c.HasBackGarden);
if(p.Key == 2 && p.Value == true)
predicate = predicate.Or (c => c.HasFrontGarden);
if(p.Key == 3 && p.Value == true)
predicate = predicate.Or (c => c.HasSecureParking);
}
ResidentialProperties.Where (predicate).Dump();
}
的foreach
循環應建立基於用戶的輸入查詢,但是當,例如,我做在字典真正的第一個值,並選擇沒有別人,它不返回任何結果。它肯定應該,因爲我知道我的數據庫表中有一些值滿足Key(1)
爲真。
我應該在query
之後做些別的什麼嗎?if
的foreach
?
編輯
我用過的謂詞建設者,而不是和它似乎是(種)當我使用predicate.Or
(按照編輯的代碼)工作,但它只返回我選擇第一個選項,它不是構建表達式樹。我認爲將predicate.Or
更改爲predicate.And
會將每個選定的用戶輸入添加到過濾器表達式中。
如果所有三個選項都是由用戶選擇的,我只希望返回HasBackGarden,HasFrontGarden和HasSecureParking列都爲true的行。我該如何做到這一點?
我只能在這裏看到'query'被指定爲'Enumerable.Empty <>'(即您的類型的空列表)。你如何將它與你要過濾的數據關聯起來? – 2013-02-20 16:49:25
我這樣做是因爲我無法去'var query;'。在Linqpad中,我正在查詢名爲ResidentialProperties的表,該表映射到名爲ResidentialProperty的模型。我需要像select一樣用'query'做些什麼嗎? – MattSull 2013-02-20 16:55:17