How do I join strings from a List<string> while also formating them?

92 views Asked by At

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.

2

There are 2 answers

0
Peter Duniho On

You can use the string.Join() overload that takes an IEnumerable<string> argument:

OU = string.Join(",",
    Web.Info.Ldap.ouList.Select(text => string.Format("OU={0}", text)));

See String.Join Method (String, IEnumerable) for more details.

0
Mike Zboray On

You are creating a few intermediate strings that aren't needed. The performance impact probably isn't all that great unless you are doing this a lot. You are allocating memory that the GC has to go and cleanup, so if there is a lot of it, collection takes longer. A more efficient approach would probably be to use StringBuilder and only create a string once when you are done.

StringBuilder builder = new StringBuilder();
foreach (string ou in Web.Info.Ldap.ouList)
{
    builder.Append("OU=").Append(ou).Append(",");
}

foreach (string dc in Web.Info.Ldap.dcList)
{
    builder.Append("DC=").Append(dc).Append(",");
}

if (builder.Length > 0)
    builder.Length--; // remove the trailing comma
string container = builder.ToString();