Farzad J Farzad J - 1 year ago 322
C# Question

How to convert PropertyValueCollection into List C# ? ( ResultPropertyCollection , SearchResult , LDAP)

I've fired a query to read some stuff from Active Directory.
But the result has some kind of "ResultPropertyCollection" as property.
Any body knows How Can I convert it to a list ( like Generic List) ?

DirectoryEntry de = new DirectoryEntry("LDAP://" + this.rootLDAP);
DirectorySearcher ds = new DirectorySearcher(de, "(& (objectcategory=Group))");


var r = ( from SearchResult sr in ds.FindAll() select sr ) .ToArray();


Answer Source

You can't - at least not very easily.

If you want to just simply have a list of SearchResult types, you could use:

var r = ds.FindAll();

List<SearchResult> results = new List<SearchResult>();

foreach (SearchResult sr in r)

But if 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 are 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 extracxt

    return returnValue;
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download