如何在LINQ select new{}中使用条件检查

本文关键字:条件 检查 LINQ select new | 更新日期: 2023-09-27 18:09:31

我想从活动目录中分配所有用户属性到列表<</p>

为此,我尝试了一些代码,但我无法在List用户管理器属性上分配Manager属性。

因为,从Active directory分配Manager属性值,我们需要在Active directory上搜索Manager用户,并且根据搜索结果,我们需要将Manager属性值分配给List of user。经理的财产。

这是我的代码,

public List< User > GetADUsers()
{
  DirectorySearcher searcher = new DirectorySearcher(ADEntry);
  searcher.Filter = "(&(objectClass=user)objectCategory=person)";      
  SearchResultCollection resultCol = searcher.FindAll();
  return 
    (from serachresult in resultCol.OfType<SearchResult>()
     let result = serachresult.GetDirectoryEntry()                       
     result.Properties["sAMAccountName"].Value != null
     select new User
     {
       GivenName = result.Properties.Contains("givenname") ?
         Convert.ToString(result.Properties["givenname"][0]) : "",
       SurName = result.Properties.Contains("sn") ?   
         Convert.ToString(result.Properties["sn"][0]) : "",
       Location = result.Properties.Contains("physicalDeliveryOfficeName") ? 
         Convert.ToString(result.Properties["physicalDeliveryOfficeName"][0]) : "",     
       Manager= ?// Here I need to assign the manager attribute from active directory
     }
    ).ToList();
}

通过使用下面提到的代码,我使用directory entry对象从Active Directory获取管理器属性。我想把这个代码放在上面提到的LINQ查询在Manager属性上。如何在LINQ Select子句中实现呢?

DirectoryEntry DomainRoot = AD.GetDirectoryEntry();
using (DirectorySearcher Search = new DirectorySearcher())
{
   Search.SearchRoot = DomainRoot;
   Search.Filter = "(&(distinguishedName=" + 
     Convert.ToString(result.Properties["manager"][0]) + "))";
   SearchResult Result = Search.FindOne();
   if (Result != null)
   {
     DirectoryEntry Manager = Result.GetDirectoryEntry();
     //This Manager.Name value I have assign above mentioned LINQ
     user.Manager = Manager.Name.Substring(3);    
     Manager.Close();
   }
}

请帮我在LINQ查询管理器属性处分配管理器名称!谢谢。

如何在LINQ select new{}中使用条件检查

尝试将您的经理计算移到一个接受'result'并返回经理名称的新函数中。然后从链接语句中调用它:Manager = GetManagerName(result)

    public string GetManagerName(DirectoryEntry dirEntry)
    {
        DirectoryEntry DomainRoot = AD.GetDirectoryEntry();
        using (DirectorySearcher search = new DirectorySearcher())
        {
            search.SearchRoot = DomainRoot;
            search.Filter = "(&(distinguishedName=" + Convert.ToString(dirEntry.Properties["manager"][0]) + "))";
            SearchResult result = search.FindOne();
            if (result != null)
            {
                using (DirectoryEntry mgr = result.GetDirectoryEntry())
                {
                    return mgr.Name.Substring(3);
                }
            }
            return string.Empty;
        }
    }