[C#LDAP SearchResult到类属性

问题描述 投票:0回答:1

我希望有人可以提供帮助。几年来,我一直在使用很多If语句遍历我的搜索结果,以填充类中的所有属性。我需要填充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。

c# ldap
1个回答
0
投票

非常简单-只需编写一个小的扩展方法,如下所示:

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%的“正常”情况,如下所示:

SearchResult result = ds.FindOne();

AgentID returnValue = new AgentID();

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

依此类推。应该not返回Properties集合的第一个元素作为字符串的任何情况,显然需要单独处理

© www.soinside.com 2019 - 2024. All rights reserved.