如何联接 List同时设置它们的格式

本文关键字:设置 格式 字符串 List 何联接 string | 更新日期: 2023-09-27 18:32:22

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

我意识到使这变得简单的一种简单方法是将"OU="和"DC="与其关联的文本存储在数据库中,.....但这对我来说只是感觉不体面。

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

"lst"列表<字符串>包含LDAP组织单位的数据行,如"帐户","用户"等

// 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 
结果:"OU=用户,OU=

帐户,OU=员工"

我对一个名为 dcList 的列表执行相同的操作,该列表生成相同类型的字符串

DC = string.Join(",", lst); 

结果:"DC=severname,DC=another_value,DC=com";

我与 OU 一起加入以获得完整的字符串,就像这样

string container = string.Join(",", OU, DC);

最终结果:"OU=Users,OU=Accounts,OU=Employees,DC=sever,DC=othervalue,DC=com"

感谢您的时间和知识。

如何联接 List<string 中的字符串>同时设置它们的格式

您可以使用

接受IEnumerable<string>参数的string.Join()重载:

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

有关更多详细信息,请参阅 String.Join 方法(字符串,IEnumerable)。

您正在创建一些不需要的中间字符串。性能影响可能不是那么大,除非你经常这样做。您正在分配 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();