HiveBrain v1.2.0
Get Started
← Back to all entries
patterncsharpMinor

Join strings from a List<string> while also formating them

Submitted by: @import:stackexchange-codereview··
0
Viewed 0 times
whileformatingjoinalsothemlistfromstringsstring

Problem

The code I have wrote works fine, this inquiry being purely for educational purposes. I want to know how others would do this better and 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 contains DataRows of LDAP Organization Units like "Accounts", "Users", etc.

// Get ou list
List lst = db.sda(sql).Rows.OfType().Select(dr => dr.Field("txt")).ToList();

string OU = string.Empty;
List lst = new List();

foreach (string ou in Web.Info.Ldap.ouList)
{
    lst.Add(string.Format("OU={0}", ou));
}
OU = string.Join(",", lst);


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

Solution

String.Join can work with IEnumerable so its not necessary to pass list to it. Same goes for foreach: you do not have to call ToList() at the end of your first query, you can loop through initial enumeration.
With LINQ you can join strings like that:

//you can call `ToList()` at the end, if you need to cache query results, but you dont have to
var fields = db.sda(sql).Rows.OfType().Select(dr => dr.Field("txt"));
//you can merge this Select with the previous one, if you are not going to re-use `fields` enumeration
var ou = fields.Select(f => "OU=" + f);
var dc = someOtherFields.Select(f => "DC=" + f);

var result = String.Join(",", ou.Concat(dc));

Code Snippets

//you can call `ToList()` at the end, if you need to cache query results, but you dont have to
var fields = db.sda(sql).Rows.OfType<DataRow>().Select(dr => dr.Field<string>("txt"));
//you can merge this Select with the previous one, if you are not going to re-use `fields` enumeration
var ou = fields.Select(f => "OU=" + f);
var dc = someOtherFields.Select(f => "DC=" + f);

var result = String.Join(",", ou.Concat(dc));

Context

StackExchange Code Review Q#71048, answer score: 5

Revisions (0)

No revisions yet.