通过DateTime对DirectorySearcher查询的结果进行排序

3

我有以下代码:

// 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();

我希望您能够将结果按照 whenCreated 属性的降序排列,以便最新的计算机对象位于顶部。
我不能简单地执行以下操作:
SortOption sortedResults = new SortOption("whenCreated", SortDirection.Descending);
dsSearch.Sort = sortedResults;

由于服务器返回错误 (http://social.technet.microsoft.com/Forums/en-US/winserverDS/thread/183a8f2c-0cf7-4081-9110-4cf41b91dcbf/),该如何解决?

最佳的解决方法是什么?

2个回答

1

如MSDN 这里所述,您可以在服务器端执行此操作。

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

该链接问题已解决:

我们在AD Windows 2008 R2上遇到了相同的问题

  • 应用了kb977180-v2http://support.microsoft.com/kb/977180
  • 并添加了密钥 HKLM\System\CurrentControlSet\Services\NTDS\Parameters
  • 添加字符串值“DSA启发式”
  • 将值设置为000000000001
  • 重启
  • 此后问题得到解决

0
创建一个比较器,通过它们的 whenCreated 属性比较 SearchResult 实例。
public class SearchResultComparer : Comparer<SearchResult>
{
    public override int Compare(SearchResult x, SearchResult y)
    {
        //Compare two SearchResult instances by their whenCreated property
    }
}

然后将所有项目复制到列表中,该列表将使用此比较器为您排序项目:

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

一般来说,我会坚持使用上述解决方案,因为在AD中进行服务器端排序既耗费资源,而且对于大型结果集来说容易出现故障。 - Brian Desmond
谢谢您的回复,我认为这会起作用。我会看看我能做什么。 - Dbloom
我最终创建了一个包含所有AD属性的类,然后创建了一个'SortedList<DateTime, CustomObject>'。这使我能够自动按日期顺序保持列表元素的顺序,并且反转顺序就像这样简单:'IEnumerable<KeyValuePair<DateTime, CustomObject>> revList = oldCompsList.Reverse();' - Dbloom

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接