2012-03-12 34 views
2

我正在嘗試將Linq查詢作爲字符串發送到在where子句中使用的方法。由於IEnumerable不適用於此,所以我已將IEnumerable轉換爲IQueryable,但仍會引發錯誤。以下是代碼:如何在linq where子句中使用字符串?

public static void FilterData(string Query) 
     { 
      if((List<MemberMaintenanceData>)HttpContext.Current.Session["Allmembers"] != null) 
      { 
       //Get the IEnumerable object colection from session 
       var data = (List<MemberMaintenanceData>) HttpContext.Current.Session["Allmembers"]; 
       //Convert it to IQueryable 
       IQueryable<MemberMaintenanceData> queryData = data.AsQueryable(); 
       //This line doesn't compile!! 
       queryData = queryData.Where(Query); 
       HttpContext.Current.Session["Allmembers"] = queryData.AsEnumerable().ToList(); 
      } 

     } 

我打算通過 「A => a.AccountId == 1000」 爲查詢

回答

1

提供類如:

public class foo 
{ 
    public int AccountID {get;set;} 
} 

你應該能夠做這樣的事情:

Expression<Func<foo, bool>> filter = f => f.AccountID == 1000; 

然後通過你的查詢。如果真的需要爲一個字符串,你可以這樣做:

filter.ToString(); 
0

有一個自由(和開源)庫,由微軟對於解析字符串成,然後可以在LINQ查詢使用Lambda表達式提供。它還包含標準查詢運算符的版本,如採用字符串參數的Where()。你可以找到它described in Scott Guthries blog post on Dynamic Linq.

例如,你可以這樣做的查詢(改編自一個片段從斯科特Guthrie的鏈接)

// imagine these have come from a drop down box or some other user input... 
string thingToSelectBy = "City"; 
string citySelectedByUser = "London"; 
int minNumberOfOrders = 10; 

string whereClause = String.Format("{0} = @0 and Orders.Count >= @1", thingToSelectBy); 

var query = db.Customers 
     .Where(whereClause, citySelectedByUser, minNumberOfOrders) 
     .OrderBy("CompanyName") 
     .Select("new(CompanyName as Name, Phone"); 

的凡thisw代碼片段子句展示瞭如何創建一個where子句使用參數化的字符串,然後在運行時爲參數動態注入值,例如,基於用戶輸入。這適用於任何類型的參數。

在你的榜樣,where子句將

whereClause = "AccountId = 1000"; 
有效

所以,你會做這樣的事情

var newFilteredQueryData = queryData.Where("AccountId = 1000"); 

該鏈接還包含在這裏你可以下載源代碼的位置,一個描述動態查詢API和表達式語言的綜合文檔。

+0

動態linq庫只適用於整數,而不是字符串,或至少我沒有看到任何使用字符串的示例。關於這個主題有很多文章和博客,所有這些文章都以整數爲例!我必須查詢的AccountId是一個字符串。 – user466663 2012-03-13 15:54:35

+0

我不確定你的意思是「只適用於整數而不是字符串」。如果您查看動態查詢語言的文檔,您會發現它適用於任何類型 - 不僅僅是整數。在我建議的鏈接頂部附近的API documetnation屏幕截圖中,它顯示了使用字符串的示例。我更新了我的答案,以表明這一點。 – 2012-03-15 08:30:29

相關問題