问题
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