Dynamic CAML Query


In his recent post Robert J Wheeler has presented his way of dealing with building CAML queries dynamically. Here at Imtech ICT Business Solutions we use a slightly different approach.

// initiate query
string whereQry = "<Where>{0}</Where>";

for (int i = 0; i < qryParams.Count; i++)
{
  // exception for last query parameter: don't add another <And>
  if (i < qryParams.Count - 1)
    whereQry = String.Format(whereQry, "<And>" + qryParams[i] +
      "{0}</And>");
  else
    whereQry = String.Format(whereQry, qryParams[i]);
}

// remove the last connector spacer
whereQry = String.Format(whereQry, String.Empty);

qry.Query = "<OrderBy><FieldRef Name='PublishingStartDate' " + 
  "Ascending='False' /></OrderBy>" + whereQry;

The first part is quite the same: we use an ArrayList to store the separate ‘And’ statements. Where the difference is, is the way we put them together. We use the String.Format method to link the separate statement to each other what keeps IMHO the code a bit more readable.

Eventually it’s not about whose code is better. It’s nice to see that other developers share our point of view on the lack of CAML support and trying to develop our own ways of dealing with it.

Others found also helpful: