2014-02-27 74 views
3

我有一個集合,我在下面查詢。在where子句中結合兩個LINQ條件

this.Collection.AsQueryable().Where(x => x.FirstName = "FirstName" && x => x.LastName= "LastName"); 

現在基於一個布爾值,我想另一個& &條件添加到where子句。

我該怎麼做呢?我嘗試了下面。

var firstExpr = x => x.FirstName = "FirstName" && x => x.LastName= "LastName"; 
var newExpr = firstExpr; 
if (includeAge) 
{ 
Expression<Func<T, bool>> ageExpr = x => x.Age == 21; 
var combined = Expression.AndAlso(ageExpr.Body, firstExpr.Body); 
var newExpr = Expression.Lambda<Func<T, bool>>(combined); 
} 

this.this.Collection.AsQueryable().Where(newExpr); 

但我得到一個異常 - System.ArgumentException:不正確的數量爲拉姆達聲明

+0

它是什麼意思,說不正確的參數數量?在newExpr上的權利? –

回答

0
var queryable = this.Collection.AsQueryable().Where(x => x.FirstName = "FirstName" && x => x.LastName= "LastName"); 

if (!includeAge) 
{ 
    return queryable; 
} 

return queryable.Where(x => x.Age == 21); 
4

提供的參數。如果這是一個收集在內存中,沒有理由轉換爲可查詢:

IEnumerable<YourType> query = this.Collection.Where(x => x.FirstName = "FirstName" && x => x.LastName= "LastName"); 

if (includeAge) 
    query = query.Where(x => x.Age == 21); 
0

這是解決您的問題的可能方案。

if (includeAge) { 
    firstExpr = firstExpr.Where(n => n.Age == 21); 
} 

除非你想在一個newExpr ......在這種情況下,你可以只保留VAR newExpr往上頂,然後將其指定爲以上。

0

也許這樣?

var persons = new Person[] { 
    new Person() { FirstName = "John", LastName = "Appleseed", IsHuman = true }, 
    new Person() { FirstName = "Compu", LastName = "Tron", IsHuman = false }, 
    new Person() { FirstName = "John", LastName = "Tron", IsHuman = false } 
          }; 

var wheres = new List<Func<Person, bool>>(); 

bool filterForJohn = true; 
bool filterForHuman = false; 

if (filterForJohn) 
    wheres.Add(new Func<Person, bool>(p => p.FirstName == "John")); 

if (filterForHuman) 
    wheres.Add(new Func<Person, bool>(p => p.IsHuman)); 

IEnumerable<Person> results = persons; 

foreach (var where in wheres) 
    results = results.Where(where); 

foreach (var p in results) 
    Console.WriteLine(p.FirstName + ' ' + p.LastName);