C# 如何连接列表中的字符串<;字符串>;同时也形成他们?

C# 如何连接列表中的字符串<;字符串>;同时也形成他们?,c#,string,ldap,domaincontroller,C#,String,Ldap,Domaincontroller,我写的代码很好,这个查询纯粹是为了教育目的。我想知道其他人如何做得更好,更干净。我特别讨厌在加入列表项之前将它们添加到另一个列表中的方式。。。。。。。。。。必须有一种更有效的方法 我意识到一个简单的方法是将“OU=”和“DC=”与其关联的文本一起存储在数据库中。。。。。但这对我来说是不体面的 我正在为LDAP调用的PrincipalContext类的容器参数构建一个字符串 “lst”列表包含LDAP组织单元的数据行,如“帐户”、“用户”等 结果:“DC=severname,DC=other_值,

我写的代码很好,这个查询纯粹是为了教育目的。我想知道其他人如何做得更好,更干净。我特别讨厌在加入列表项之前将它们添加到另一个列表中的方式。。。。。。。。。。必须有一种更有效的方法

我意识到一个简单的方法是将“OU=”和“DC=”与其关联的文本一起存储在数据库中。。。。。但这对我来说是不体面的

我正在为LDAP调用的PrincipalContext类的容器参数构建一个字符串

“lst”列表包含LDAP组织单元的数据行,如“帐户”、“用户”等

结果:“DC=severname,DC=other_值,DC=com”

我和OU连接起来得到完整的字符串,就像这样

string container = string.Join(",", OU, DC);
最终结果:“OU=用户,OU=帐户,OU=员工,DC=服务器,DC=其他值,DC=com”


感谢您的时间和知识。

您可以使用带有
IEnumerable
参数的
string.Join()
重载:

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

有关更多详细信息,请参阅。

您正在创建一些不需要的中间字符串。除非您经常这样做,否则对性能的影响可能不会太大。您正在分配GC必须执行和清理的内存,因此如果内存太多,则收集需要更长的时间。一种更有效的方法可能是使用
StringBuilder
,并且在完成后只创建一次字符串

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();

如果你的代码工作,你寻求改进,考虑张贴,而不是堆栈溢出。谢谢,不知道有这样的事情。
OU = string.Join(",",
    Web.Info.Ldap.ouList.Select(text => string.Format("OU={0}", text)));
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();