enum MergeType { Or, And };
/// <summary>
/// Use this method to merge multiple Or, And condition in same CAML query for same or different columns
/// </summary>
/// <param name="conditions"></param>
/// <param name="type"></param>
/// <returns></returns>
private string MergeCAMLConditions(List<string> conditions, MergeType type)
{
try
{
if (conditions.Count == 0) return "";
string typeStart = (type == MergeType.And ? "<And>" : "<Or>"); string typeEnd = (type == MergeType.And ? "</And>" : "</Or>");
// Build hierarchical structure
while (conditions.Count >= 2)
{
List<string> complexConditions = new List<string>();
for (int i = 0; i < conditions.Count; i += 2)
{
if (conditions.Count == i + 1)
// Only one condition left
complexConditions.Add(conditions[i]);
else
// Two condotions - merge
complexConditions.Add(typeStart + conditions[i] + conditions[i + 1] + typeEnd);
}
conditions = complexConditions;
}
}
catch (Exception exec)
{
logger.WriteEventLog("Please contact admin : " + exec.Message);
throw exec;
}
return conditions[0];
}
How to use this method:
List<string> conditions = new List<string>();
foreach (string id in ids)
{
conditions.Add("<Eq><FieldRef Name='Model' /><Value Type='Text'>" + id + "</Value></Eq>");
}
string merged = MergeCAMLConditions(conditions, MergeType.Or);
string viewXml = @"<View Scope='Recursive'>
<Query><Where>" + merged +
@"</Where></Query>
</View>";
camlQuery.ViewXml = viewXml;
/// <summary>
/// Use this method to merge multiple Or, And condition in same CAML query for same or different columns
/// </summary>
/// <param name="conditions"></param>
/// <param name="type"></param>
/// <returns></returns>
private string MergeCAMLConditions(List<string> conditions, MergeType type)
{
try
{
if (conditions.Count == 0) return "";
string typeStart = (type == MergeType.And ? "<And>" : "<Or>"); string typeEnd = (type == MergeType.And ? "</And>" : "</Or>");
// Build hierarchical structure
while (conditions.Count >= 2)
{
List<string> complexConditions = new List<string>();
for (int i = 0; i < conditions.Count; i += 2)
{
if (conditions.Count == i + 1)
// Only one condition left
complexConditions.Add(conditions[i]);
else
// Two condotions - merge
complexConditions.Add(typeStart + conditions[i] + conditions[i + 1] + typeEnd);
}
conditions = complexConditions;
}
}
catch (Exception exec)
{
logger.WriteEventLog("Please contact admin : " + exec.Message);
throw exec;
}
return conditions[0];
}
How to use this method:
List<string> conditions = new List<string>();
foreach (string id in ids)
{
conditions.Add("<Eq><FieldRef Name='Model' /><Value Type='Text'>" + id + "</Value></Eq>");
}
string merged = MergeCAMLConditions(conditions, MergeType.Or);
string viewXml = @"<View Scope='Recursive'>
<Query><Where>" + merged +
@"</Where></Query>
</View>";
camlQuery.ViewXml = viewXml;
No comments:
Post a Comment