C# LDAP SearchResult 到 class 属性

C# LDAP SearchResult to class properties

我希望有人能帮助解决这个问题。几年来,我一直在使用大量 If 语句遍历我的搜索结果,以填充我的 class 中的所有属性。我需要填充 300 多个属性……但是 if 语句太多了。例如,这就是我的意思:

            var myCon = StarfishLDAPCon.CreateDirectoryEntry(objectContainer, whichCM);
            var ds = new DirectorySearcher(myCon);
            ds.Filter = "(deftyAgentID=07629)";
            var result = ds.FindOne();


            AgentID returnValue = new AgentID();

            if (result.Properties.Contains("deftyAgentID"))
            {
                returnValue.DeftyAgentID = result.Properties["deftyAgentID"][0].ToString();
            }

            if (result.Properties.Contains("deftySecuritycode"))
            {
                returnValue.DeftyAgentID = result.Properties["deftySecuritycode"][0].ToString();
            }

            if (result.Properties.Contains("deftyAgentACWAgentConsdrdIdle"))
            {
                returnValue.DeftyAgentACWAgentConsdrdIdle = result.Properties["deftyAgentACWAgentConsdrdIdle"][0].ToString();
            }

我有 300 多个 if 语句。我希望有一些很酷的方法可以在没有所有这些 if 语句的情况下做到这一点?有人有什么想法吗?

感谢您的帮助!

戴夫·M.

嗯,很简单 - 只需编写一个像这样的小扩展方法:

public static class SearchResultExtension
{
    public string GetPropertyValue(this SearchResult result, string propName)
    {
        if (result == null || result.Properties == null)
        {
            return null;
        }

        if (result.Properties.Contains(propName))
        {
            return result.Properties[propName][0].ToString();
        }

        return null; 
    }
}

现在您可以像这样处理 80% "normal" 个案例:

SearchResult result = ds.FindOne();

AgentID returnValue = new AgentID();

returnValue.DeftyAgentID = result.GetPropertyValue("deftyAgentID");
returnValue.DeftySecurityCode = result.GetPropertyValue("deftySecuritycode");
returnValue.DeftyAgentACWAgentConsdrdIdle = result.GetPropertyValue("deftyAgentACWAgentConsdrdIdle");

等等。任何应该 not return Properties 集合的第一个元素作为字符串的情况都需要单独处理,显然