2010-09-03 111 views
1

我想根據用戶選擇動態過濾記錄。用戶可以選擇顯示大於借方的借方金額或高於借方的貸方金額。因此我想提出一個條件相似,無論是totDebit>totCredit or TotCredit> totDebit`linq查詢動態添加條件?

Dim query = _ 
     From product In Bills.AsEnumerable() _ 
     Group product By accode = product.Field(Of String)("ACCODE"), _ 
     BILLNO = product.Field(Of String)("BILLNO") Into g = Group _ 
     Let totDebit = g.Sum(Function(proudct) proudct.Field(Of Decimal)("DEBIT")) _ 
     Let totCredit = g.Sum(Function(proudct) proudct.Field(Of Decimal)("CREDIT")) _ 
     Select New With _ 
     { _ 
      .ACCODE = accode, _ 
      .billno = BILLNO, _ 
      .TOTALDEBIT = totDebit, _ 
      .TOTALCREDIT = totCredit, _ 
      .BALNACE = totDebit - totCredit _ 
      } 

如何才能做到這一點?

回答

1

我認爲你正在尋找動態查詢庫。未列入的LINQ但availble的從斯科特Guthrie的博客下載:

http://weblogs.asp.net/scottgu/archive/2008/01/07/dynamic-linq-part-1-using-the-linq-dynamic-query-library.aspx

無論是VB和C#DynamicQuery 樣品包括源 實現一個輔助庫 ,讓你表達LINQ 查詢使用擴展方法 需要字符串參數而不是 類型安全的語言運算符。

您可以將字符串過濾exection:

myData.DynamicWhere(string.Format("{0}.Contains(\"{1}\")", filter.field, filter.data.value)); 
1

在你等皆shownm你只是建立了一個查詢碼;你還沒有執行它。而且,在任何時候,你EXCUTE它之前,你可能會繼續構建它:

Dim query = _ 
    From product In Bills.AsEnumerable() _ 
    Group product By accode = product.Field(Of String)("ACCODE"), _ 
    ' etc as above.... 

    If onlyCredits Then 
     query = query.Where(Function(proudct) product.TOTALCREDIT > product.TOTALDEBIT) 
    Elseif onlyDebits Then 
     query = query.Where(Function(proudct) product.TOTALCREDIT < product.TOTALDEBIT) 
    Endif 

注意,我是一個C#的傢伙,所以請原諒小的語法錯誤....