Search code examples
vb.netlinqlinq-to-sql

Dynamic clause where in Linq to Datatable


I have a query that select some rows from datatable,but the clause where is concatenated according to many test, bellow what i have tried but he didn't work :

Dim queryArchi = (From b In DataBien.AsEnumerable()
    Group b By b!nom_ville, b!Designation_projet, b!code_ville, b!code_projet Into Group
     Select nom_ville, Designation_projet,code_ville, code_projet, NBP = Group.Count())

      If vil <> "" Then queryArchi = queryArchi.Where(Function(d) d.code_ville = vil) 
      If p > 0 Then queryArchi.Where(Function(d)  d.code_projet.Equals(p))                    
           queryStructure = queryArchi.ToList

Only the first test is working :

   If vil <> "" Then queryArchi = queryArchi.Where(Function(d) d.code_ville = vil)

Solution

  • Look at these two rows:

    If vil <> "" Then queryArchi = queryArchi.Where(Function(d) d.code_ville = vil) 
    If p > 0 Then queryArchi.Where(
    

    Don't you see the difference? There is a missing queryArchi =

    So

    If p > 0 Then queryArchi = queryArchi.Where(
    

    LINQ operators don't "modify" the original query, they simply return a "new" query with the LINQ operator "added".