This documentation is archived and is not being maintained.

SPContentTypeCollection.BestMatch Method

Windows SharePoint Services 3

Searches the collection and returns the SPContentTypeId object that is the nearest match to the specified SPContentTypeId object.

Namespace:  Microsoft.SharePoint
Assembly:  Microsoft.SharePoint (in Microsoft.SharePoint.dll)

public SPContentTypeId BestMatch(
	SPContentTypeId contentTypeId
)

Parameters

contentTypeId
Type: Microsoft.SharePoint.SPContentTypeId
An SPContentTypeId object to match.

Return Value

Type: Microsoft.SharePoint.SPContentTypeId
An SPContentTypeId object that is the value of the Id property for the content type with the closest match. Note that 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.

You can 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: