I was working on a solution to find items by its content type throughout site collection using SPSiteDataQuery. I would suggest using Content Type ID instead querying using content type name as I found it breaks when move to other UAT or Production environments.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
using System; | |
using System.Collections.Generic; | |
using System.Linq; | |
using System.Text; | |
using System.Threading.Tasks; | |
using Microsoft.SharePoint; | |
using System.Data; | |
namespace EventCamlConsole | |
{ | |
class Program | |
{ | |
static void Main(string[] args) | |
{ | |
using (SPSite osite = new SPSite("http://your_site_url_here/")) | |
{ | |
using (SPWeb oweb = osite.RootWeb) | |
{ | |
Console.WriteLine("--------------------------------------"); | |
Console.WriteLine("Tests execution..."); | |
SPSiteDataQuery query = new SPSiteDataQuery(); | |
query.Webs = "<Webs Scope=\"Recursive\">"; | |
query.Lists = "<Lists BaseType='1' MaxListsLimit='0'/>"; | |
query.ViewFields = "<FieldRef Name='Title' />"; | |
SPContentType cTypeCollection = oweb.ContentTypes["Content_Type_Name"]; | |
string where = string.Format( | |
@"<Where> | |
<BeginsWith> | |
<FieldRef Name='ContentTypeId'/> | |
<Value Type='Text'>{0}</Value> | |
</BeginsWith> | |
</Where>", cTypeCollection.Id); | |
// Set the query string. | |
query.Query = where; | |
DataTable results = oweb.GetSiteData(query); | |
foreach (DataRow row in results.Rows) | |
{ | |
Console.WriteLine("{0}", row["Title"]); | |
} | |
} | |
} | |
} | |
} | |
} | |