我想从AD获得唯一或不同的部门名称,那么对此的正确查询是什么。以下是我的代码:
private static DomainController GetDomainController(string domainpath)
{
var domainContext = new DirectoryContext(DirectoryContextType.Domain, domainpath);
var domain = Domain.GetDomain(domainContext);
var controller = domain.FindDomainController();
return controller;
}
private static MyMethod()
{
var domainController = GetDomainController(ActiveDirectorySettings.DomainPath);
// Lookup the information in AD
var ldapEntry = new DirectoryEntry(string.Format("LDAP://{0}", domainController)) { AuthenticationType = AuthenticationTypes.Secure | AuthenticationTypes.FastBind };
DirectorySearcher ds;
ds = new DirectorySearcher(ldapEntry)
{
SearchScope = SearchScope.Subtree,
Filter = "(&" + "(objectClass=user)" + "(department=" + departmentname + "*))"
};
ds.PropertiesToLoad.Add("department");
if (ds.FindAll().Count >= 1)
{
//do something....
}
}
这里我得到所有部门名称,包括重复。但我想要的是 -
如果3个用户属于同一个部门(X),那么我想要部门(X)一次不是三次。
答案 0 :(得分:3)
您可以使用LINQ获取唯一/不同的搜索结果。以下是代码段:
if (ds.FindAll().Count >= 1)
{
var overallSearchResult = ds.FindAll();
//to apply distinct on path property of elements in the collection
var uniqueSearchResultsForPath = overallSearchResult.Cast<System.DirectoryServices.SearchResult>().Select(x => x.Path).Distinct();
//To apply distinct on any specific property in the "Properties" property of the elements in the collection
//this will give you list of distinct departments for example
var uniqueSearchResultsForDepartment = overallSearchResult.Cast<System.DirectoryServices.SearchResult>().Select(x => x.Properties["department"][0]).Distinct();
}
您必须在编写此代码的C#文件中包含using System.Linq;
命名空间。