2010-09-03 113 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#的家伙,所以请原谅小的语法错误....