The code I have wrote works fine, this inquiry is purely for educational purposes. I want to know how others would do this better, cleaner. I especially hate the way I add the list items to another list before they are joined .......... there has to be a more efficient way.
I realize an easy way to make this simple would be to store "OU=" and "DC=" in the database with their associated text, ..... but that just feels unseemly to me.
I am building a string for the container argument of the PrincipalContext class for an LDAP call.
The "lst" List<string> contains DataRows of LDAP Organization Units like "Accounts", "Users", etc
// Get ou list
List<string> lst = db.sda(sql).Rows.OfType<DataRow>().Select(dr => dr.Field<string>("txt")).ToList()
string OU = string.Empty;
List<string> lst = new List<string>();
foreach (string ou in Web.Info.Ldap.ouList)
{
lst.Add("OU=" + ou); // 6th revision .... this works, but wasn't as good as I thought it should be
lst.Add(string.Format("OU={0}", ou)); // 7th revision .... this works as well, but I thought it could be done better, which is why I am here.
}
OU = string.Join(",", lst); // born of 6th revision, used in 7th also
Result: "OU=Users,OU=Accounts,OU=Employees"
I do the same thing to a list called dcList that produces the same kind of string
DC = string.Join(",", lst);
Result: "DC=severname,DC=another_value,DC=com";
to which I join together with OU to get the complete string, like so
string container = string.Join(",", OU, DC);
End result: "OU=Users,OU=Accounts,OU=Employees,DC=sever,DC=othervalue,DC=com"
Thanks for your time and knowledge.
You can use the
string.Join()
overload that takes anIEnumerable<string>
argument:See String.Join Method (String, IEnumerable) for more details.