2010-02-25 65 views
4

我們可以動態地在LINQ查詢條件的位置上?如何使用條件

例如:

class Result 
{ 
     string v1; 
     string v2; 
     string v3; 
} 

List<Result> result = (from r in results select r); 


//i want to do something like the following.... 

if(conditionA) 
{ 
    result = result appened (or v1 = xxx) 
} 
else if(conditionB) 
{ 
    result = result appened (or v2 = xxx) 
} 
else if(conditionC) 
{ 
    result = result appened (or v3 == xxx) 
} 

任何人都知道如何處理Linq中的條件????

回答

1

對於and關係的子句,你可以很容易地只是追加了.Where()過濾方法,因爲這樣的:

where conditionOriginal(r) and conditionDynamic(r) 

var results = (from r in originalResults 
       where originalConditions(r) 
       select r); 
... 
if (conditionA) 
    results = results.Where(r => conditionDynamic(r)); 

要追加一個「或」類型的關係,但是,你不得不工會與原來的結果集,像這樣:

where conditionOriginal(r) or conditionDynamic(r) 

成爲

var results = (from r in originalResults 
       where conditionOriginal(r) 
       select r); 
... 
if (conditionB) 
    results = results.Union((from r in originalResults 
          where conditionDynamic(r) 
          select r)); 

if (conditionB) 
    results = results.Union(originalResults.Where(conditionDynamic(r))); 
1

Where查詢運營商只需添加到您的查詢:

if(conditionA) 
{ 
    result = result.Where(r => r.v1 == xxx); 
} 
else if(conditionB) 
{ 
    result = result.Where(r => r.v2 == xxx); 
} 
else if(conditionC) 
{ 
    result = result.Where(r => r.v3 == xxx); 
} 

請注意,您results變量應被聲明爲IEnumerable<Result>,不List<Result>

+0

怎麼樣的關係ship..some是,有些是或 – jojo 2010-02-25 00:59:36

+0

哦,對了,我沒有注意到.... thekaido的回答可以幫助你,然後 – 2010-02-25 01:27:25

1

你可以這樣做:

if (conditionA) 
{ 
    result = result.Where(p => p.v1 == xxx); // Just guessing at the intent here. 
} 
// Repeat as necessary... 

或者這樣:

if (conditionA) 
{ 
    result = from r in result where p.v1 == xxx select r; 
} 
0

由於LINQ的將推遲執行,你可以在那裏追加到您的查詢,並調用tolist到底執行:

var query = from r in results; 

//i want to do something like the following.... 

if(conditionA) 
{ 
    query = result.Where(x => x.v1 = xxx); 
} 
else if(conditionB) 
{ 
    query = result.Where(x => x.v2 = xxx); 
} 
else if(conditionC) 
{ 
    query = result.Where(x => x.v1 = xxx); 
} 

List<Result> result = query.ToList(); 
0

那麼,你可以隨時撥打where子句中的功能,並有建立自己的條件:

... 
public bool MeetsConditions(Result r, bool a, bool b) 
{ 
    bool result = false; 
    if(a) result = result || r.v1==xxx 
    if(b) result = result && r.v2==xxx 
    return result; 
} 
... 
var q = select from r in results where MeetsConditions(r, conditionA, conditionB) 
+0

但我需要動態地創建條件...「結果」是一個樣本..我將有很多這種類型的對象 – jojo 2010-02-25 01:04:35

3

如果你想動態構建它,你可以使用 PredicateBuilder

+0

+1我已經使用PredicateBuilder的規範模式取得了巨大的成功。 – Luhmann 2010-02-25 00:40:22