Alternate to CAML Or

In is a lesser known CAML operator that I’d like to bring to more peoples attention. When writing CAML and you want to restrict the results by a multi value field equaling two or more values, you’d write something like:

<Where>
<Or>
  <Or>
    <Eq>
      <FieldRef Name="Country" /><Values><Value Type="LookupMulti">Scotland</Value></Values>
    <Eq>
    <Eq>
      <FieldRef Name="Country" /><Values><Value Type="LookupMulti">England</Value></Values>
    <Eq>
  </Or>
  <Or>
    <Eq>
      <FieldRef Name="Country" /><Values><Value Type="LookupMulti">Wales</Value></Values>
    <Eq>
    <Eq>
      <FieldRef Name="Country" /><Values><Value Type="LookupMulti">Ireland</Value></Values>
    <Eq>
  </Or>
</Or>
</Where>

This will return any item that has the value Scotland, England, Wales or Ireland in the Country field. As the number of values you want to match against grows, imagine the state of the CAML query!

Using the In condition instead, the above CAML can be simplified to the following:

<Where>
  <In>
    <FieldRef Name="Country" />
    <Values>
      <Value Type="LookupMulti">Scotland</Value>
      <Value Type="LookupMulti">England</Value>
      <Value Type="LookupMulti">Wales</Value>
      <Value Type="LookupMulti">Ireland</Value>
    </Values>
  </In>
</Where>

A lot smaller and easier to read, don’t you agree?

The In condition can be used with any field type, doesn’t have to be multi valued types like LookupMulti or MultiChoice. When used against a Text field, for example, it simply replaces the Eq condition. Not that much benefit to using it this way though as it’s not making your life any easier.

Leave a Reply

Your email address will not be published. Required fields are marked *

Solve the maths problem shown below before posting: *

Follow

Get every new post delivered to your Inbox

Join other followers: