Sorting DirectorySearcher query results by DateTime

I have the following code:

// Declare new DirectoryEntry and DirectorySearcher
DirectoryEntry domainRoot = new DirectoryEntry("LDAP://rootDSE");
string rootOfDomain = domainRoot.Properties["rootDomainNamingContext"].Value.ToString();
DirectorySearcher dsSearch = new DirectorySearcher(rootOfDomain);

// Set the properties of the DirectorySearcher
dsSearch.Filter = "(objectClass=Computer)";
dsSearch.PropertiesToLoad.Add("whenCreated");
dsSearch.PropertiesToLoad.Add("description");
dsSearch.PropertiesToLoad.Add("operatingSystem");
dsSearch.PropertiesToLoad.Add("name");

// Execute the search
SearchResultCollection computersFound = dsSearch.FindAll();

I want to sort the results using a property whenCreatedin descending order, so the latest computer objects are at the top.

I just can not:

SortOption sortedResults = new SortOption("whenCreated", SortDirection.Descending);
dsSearch.Sort = sortedResults;

because the server returns an error (http://social.technet.microsoft.com/Forums/en-US/winserverDS/thread/183a8f2c-0cf7-4081-9110-4cf41b91dcbf/)

What is the best way to sort?

+3
source share
2 answers

Create a mapping that compares SearchResult instances using the whenCreated property

public class SearchResultComparer : Comparer<SearchResult>
{
    public override int Compare(SearchResult x, SearchResult y)
    {
        //Compare two SearchResult instances by their whenCreated property
    }
}

and then copy all the items to the list that this comparator will use to sort the items for you:

List<SearchResult> SearchResultList = new List<SearchResult>(computersFound);
SearchResultList.Sort(new SearchResultComparer());
0
source

, MSDN :

      new DirectorySearcher(entry)
      {
        Sort = new SortOption("cn", SortDirection.Ascending),
        PropertiesToLoad = {"cn"}
      };

:

AD Windows 2008 R2

0

All Articles