Nested CAML queries with multiple ORs or ANDs

Sometimes is Linq2SharePoint just not an option. Unfortunately.

I don’t know how many times I have written methods which build nested CAML queries for multiple ORs or ANDs (when you have to OR more than two values). And of course I always forget where it was. This time it goes to the blog. Voila.

private static string makeQuery()
{
try
{

int[] ids = new int[] { 1, 9, 13, 15};

string fieldName = "ID"; //the field we are comparing
string valueType = "Counter"; //type of the field -> "Counter" for ID.
string logicalOperator = "Or"; //logical operator
string comparisonOperator = "Eq"; //the comparison operator

StringBuilder sb = new StringBuilder();

if (ids.Length == 1)
{
sb.Append(elementComparisonString(fieldName, valueType, comparisonOperator, ids[0]));
}

if (ids.Length == 2)
{
sb.Append(logicalOperation(logicalOperator, elementComparisonString(fieldName, valueType, comparisonOperator, ids[0]), elementComparisonString(fieldName, valueType, comparisonOperator, ids[1])));
}

if (ids.Length > 2)
{
string buildQuery = logicalOperation(logicalOperator, elementComparisonString(fieldName, valueType, comparisonOperator, ids[0]), elementComparisonString(fieldName, valueType, comparisonOperator, ids[1]));

for (int ii = 2; ii < ids.Length; ii++)
{
int id = ids[ii];

string se = elementComparisonString(fieldName, valueType, comparisonOperator, id);

buildQuery = logicalOperation(logicalOperator, se, buildQuery);
}

sb.Append(buildQuery);
}

sb.Append("");

return "" + sb.ToString();
}
catch (Exception ex)
{
throw new ApplicationException("Error building nested CAML query", ex);
}
}

///

<summary>/// builds a caml logical operation between two strings (which have to be comparison elements between two values, or previously built logical operation
///
</summary>

///Logical operator - Or, And... ///First string to perform logical operation ///Second string to perform logical operation /// Built logical operation string
private static string logicalOperation(string logicalOperator, string singleElement1, string singleElement2)
{

string logOp = string.Format("{1}{2}", logicalOperator, singleElement1, singleElement2);

return logOp;
}

///

<summary>/// Method which builds a caml comparison string for a value
///
</summary>

///name of the field ///type of the field ///comparison operator ///value which the element should have /// Result example: 1
/// element comparison string
private static string elementComparisonString(string fieldName, string valueType, string comparisonOperator, int elementValue)
{
string singleQuery = string.Format("{2}", fieldName, valueType, elementValue.ToString(), comparisonOperator);

return singleQuery;
}