Querying content based on its Content Type

It’s almost always required to show SharePoint content based on the Content Type it implements, like a Page or a List Item.
And as you guess, the best approach would be to build a query to retrieve those items, just specifying the ContentType name or Id.
Here you have an example, I will use SPSiteDataQuery since I’m looking for content all across the Site Collection:

 <Where>    <Eq>     <FieldRef Name='ContentType' />     <Value Type='Text'>MyCustomContentType</Value>    </Eq> </Where>  

Using queryText as the query above

  SPSiteDataQuery query = new SPSiteDataQuery();  query.RowLimit = 100; query.Lists = "<Lists ServerTemplate=\"850\" />"; //850 Page Library query.Webs = "<Webs Scope=\"SiteCollection\" />"; ViewFields = "<FieldRef Name=\"Title\" />"; query.Query = queryText;  

But, what happen if, for instance, we have a not too simple Content Type name that includes a character like ‘&’?.
We should be calling Houston, because SharePoint Query Engine lacks of a query pre-interpreter.
If that’s the case, we have two options:

-Use the ContentTypeId field, instead of ContentType

 <Where>    <Eq>     <FieldRef Name='ContentTypeId' />     <Value Type='ContentTypeId'>0x0100DC485599A8AC4F70B22792A20E7E5080</Value>    </Eq> </Where> 

-Use the ContentType name field and declare it as CDATA, replacing it later by using string.Format

 <Where>    <Eq>     <FieldRef Name='ContentType' />     <Value Type='Text'><![CDATA[{0}]]></Value>    </Eq> </Where> 

In my opinion, the best solution is to use the Content Type Id, and use the Content Type name when it’s really needed.
Choose the one you want to use!

Leave a Reply

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

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <s> <strike> <strong>