Write CAML queries in code

In my very first webpart that I wrote I needed to write some CAML queries to filter and sort the lists.

Being the type of guy who hates seeing strings littering my code I searched the net for an API for CAML queries. Thankfully John Holliday had already done the hard work and created CAML.NET. Check out the clean syntax for the CAML code.

   1: string typeName = "My Content Type";
   2: string simpleQuery =
   3:     CAML.Query(
   4:         CAML.Where(
   5:             CAML.Or(
   6:                 CAML.Eq(
   7:                     CAML.FieldRef("ContentType"), 
   8:                     CAML.Value(typeName)),
   9:                 CAML.IsNotNull(
  10:                     CAML.FieldRef("Description")))),
  11:         CAML.GroupBy(
  12:             true,
  13:             CAML.FieldRef("Title",CAML.SortType.Descending)),
  14:         CAML.OrderBy(
  15:             CAML.FieldRef("_Author"),
  16:             CAML.FieldRef("AuthoringDate"),
  17:             CAML.FieldRef("AssignedTo",CAML.SortType.Ascending))
  18:     );

Here again you might run into the issue of adding an extra assembly to your deployment, the simple alternative that I took was to include the CAML class directly into me source tree. But remember to keep the copyright and license header in place as stated by the Ms-CL license.

Hopefully Microsoft will release a Linq to CAML library soon, there is already one at CodePlex by a Microsoft employee but what would be better is if it comes with SharePoint.

Write CAML queries in code

2 thoughts on “Write CAML queries in code

  1. Hhe article's content rich variety which make us move for our mood after reading this article. surprise, here you will find what you want! Recently, I found some wedsites which commodity is colorful of fashion. Such as http://www.always11.net that worth you to see. Believe me these websites won’t let you down.

  2. Mark S. is definitely on the right track. If you want to get a professional looking email address, Id recommend buying your name domain name, like or
    ajf 13
    If its common it might be difficult to get, however, be creative and you can usually find something.

Comments are closed.