Sorting on directorySearcher based on two properties in c#

人盡茶涼 提交于 2021-01-29 07:19:12

问题


I'm trying to get a sorted SearchResultCollection object based on department, and then by name (both alphabetical). I'm trying to load two properties, but this merely takes the last property specified and sorts it based on that.

My current code is the following:

DirectoryEntry entry = new DirectoryEntry(ConfigurationManager.AppSettings["LDAP"]);
DirectorySearcher search = new DirectorySearcher(entry)
{
    SearchScope = SearchScope.Subtree,
    Filter = "(&(objectClass=user)(physicalDeliveryOfficeName=Dartmouth))"
};
search.PropertiesToLoad.Add("name");
search.PropertiesToLoad.Add("phone");
search.PropertiesToLoad.Add("email");
search.PropertiesToLoad.Add("department");

search.Sort.Direction = System.DirectoryServices.SortDirection.Ascending;
search.Sort.PropertyName = "department";
search.Sort.PropertyName = "name";

SearchResultCollection result = search.FindAll(); 

But again, this only sorts by name. I need all users grouped by department, and from there sorted by name.


回答1:


Cast the SearchResultCollection to an IEnumerable and then sort with a custom IComparer that you develop

var results = search.FindAll().Cast<SearchResult>()
                              .Sort(/*your IComparer<SearchResult>*/);

Sort the results on client side because server side sorts in AD are resource intensive.

In addition - if you have AD 2000 it doesn't support search on more than one attribute



来源:https://stackoverflow.com/questions/38351147/sorting-on-directorysearcher-based-on-two-properties-in-c-sharp

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!