1

I hope someone can help with this. For a few years now, I've been iterating through my searchresult using a LOT of If statements to populate all of the properties in my class. There are over 300 properties that I need to populate.. but that is an awful lot of if statements. As an example, this is what I mean:

            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();
            }

I have over 300 of those if statements. I'm hoping there's some cool way to do this without all those if statements? Anyone have any ideas?

Thanks for any help!

Dave M.

DaveM
  • 93
  • 1
  • 5

1 Answers1

0

Well pretty simple - just write a small extension method like this:

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; 
    }
}

Now you can handle the 80% "normal" cases like this:

SearchResult result = ds.FindOne();

AgentID returnValue = new AgentID();

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

and so forth. Any cases that should not return the first element of the Properties collection as a string need to be handled separately, obviously

marc_s
  • 732,580
  • 175
  • 1,330
  • 1,459
  • This is about the best you can do. Unlike with `DirectoryEntry`, with `SearchResult`, `Properties["somethingBogus"]` does not return `null`, so you can't even use the null conditional operator. I would only suggest not using `.ToString()` in the extension method so you can use it for other types too, then just cast to the type you need, like `(string) result.GetPropertyValue("deftyAgentID")` (fun fact: [casting to `string` is *slightly* faster than `.ToString()`](https://stackoverflow.com/a/1170765/1202807)) – Gabriel Luci Jun 07 '20 at 00:32