Export (0) Print
Expand All

SPContentTypeCollection.BestMatch Method

Searches the collection and returns the content type identifier (ID) that is the nearest match to the specified content type ID.

Namespace:  Microsoft.SharePoint
Assembly:  Microsoft.SharePoint (in Microsoft.SharePoint.dll)
Available in Sandboxed Solutions: Yes
Available in SharePoint Online

public SPContentTypeId BestMatch(
	SPContentTypeId contentTypeId
)

Parameters

contentTypeId
Type: Microsoft.SharePoint.SPContentTypeId

A content type ID to match.

Return Value

Type: Microsoft.SharePoint.SPContentTypeId
The value of the Id property for the content type with the closest match to the value of the specified content type ID. If the search finds two matches, the shorter ID is returned. For example, if 0x0101 is the argument, and the collection contains both 0x010109 and 0x01010901, the method returns 0x010109.

Use this method to determine if a collection contains a child of a known content type. Keep in mind, however, that when a site content type is copied to a list, the content type in the list gets a new content type ID in the following form.

site content type ID + “00” + 32-character hexadecimal GUID

For more information, see Content Type IDs.

TipTip

If you want to know everywhere that a content type is used throughout a site collection, call the GetUsages method.

The following example shows a console application that iterates through the lists in a Web site and determines whether or not the content type collection of each list contains a descendant of a specified content type.

using System;
using Microsoft.SharePoint;

namespace Test
{
   class ConsoleApp
   {
      static void Main(string[] args)
      {
         using (SPSite siteCollection = new SPSite("http://localhost"))
         {
            using (SPWeb webSite = siteCollection.OpenWeb())
            {
               // Get a content type id to search for.
               SPContentTypeId contentTypeId = SPBuiltInContentTypeId.Task;

               foreach (SPList list in webSite.Lists)
               {
                 if (ListContains(list, contentTypeId))
                    Console.WriteLine("The {0} list uses the content type.", 
                                       list.Title);
               }
            }
         }
         Console.Write("\nPress ENTER to continue...");
         Console.ReadLine();
      }

      static bool ListContains(SPList list, SPContentTypeId id)
      {
         SPContentTypeId matchId = list.ContentTypes.BestMatch(id);
         return matchId.IsChildOf(id);
      }
   }
}

The application prints the following output to the console.

The Tasks list uses the content type.

Press ENTER to continue...
Show:
© 2014 Microsoft