Friday 20 January 2023

How to convert PropertyValueCollection into a List C# ? (ResultPropertyCollection and SearchResult)

 

I've written a query to read some stuff from Active Directory, but the result is some kind of "ResultPropertyCollection", which is something I'm not familiar with.

How can I convert this result to a list (like Generic List) that I'm more familiar with so I can do something with the results?

DirectoryEntry de = new DirectoryEntry("LDAP://" + this.rootLDAP);
    DirectorySearcher ds = new DirectorySearcher(de, "(& (objectcategory=Group))");
    
    ds.PropertiesToLoad.Add("samaccountname");
    ds.PropertiesToLoad.Add("memberof");
    ds.PropertiesToLoad.Add("samaccounttype");
    ds.PropertiesToLoad.Add("grouptype");
    ds.PropertiesToLoad.Add("member");
    ds.PropertiesToLoad.Add("objectcategory");
     
     var r = ( from SearchResult sr in ds.FindAll() select sr ) .ToArray();
 
           

If you only want a list of SearchResult types, you could use:

var r = ds.FindAll();
        
List<SearchResult> results = new List<SearchResult>();

foreach (SearchResult sr in r)
{
   results.Add(sr);
}

But since you want the actual values from the search results, you need to do more work.

Basically, that collection contains all the properties you've defined for the search - at least as long as they contain a value!

So really, what you need to do is create a class to hold those values. The two elements memberOf and member can themselves contain multiple values (they're "multi-valued" attributes in AD) - so you'll need a list of strings for these:

public class YourType
{
    public string SamAccountName { get; set; }
    public int SamAccountType { get; set; }
    public int GroupType { get; set; }
    public string ObjectCategory { get; set; }
    public List<string> MemberOf { get; set; }
    public List<string> Member { get; set; }
}

Then, once you have your search result, you need to iterate over the results and create new instances of YourType for each search result, and stick those into a List<YourType>:

foreach(SearchResult sr in ds.FindAll())
{
    YourType newRecord = ConvertToYourType(sr);
}

and in that method, you need to inspect the .Properties collection for each value and extract it:

public YourType ConvertToYourType(SearchResult result)
{
    YourType returnValue = new YourType();
    returnValue.MemberOf = new List<string>();
    returnValue.Member = new List<string>();

    if(result.Properties["samAccountName"] != null && result.Properties["samAccountName"].Count > 0)
    {
       returnValue.SamAccountName = result.Properties["samAccountName"][0].ToString();
    }

    // ..... and so on for each of your values you need to extract

    return returnValue;
}
 

No comments:

Post a Comment

Note: only a member of this blog may post a comment.