gpt4 book ai didi

c# - 在 C# 中,检查 stringbuilder 是否包含子字符串的最佳方法

转载 作者:可可西里 更新时间:2023-11-01 09:11:20 29 4
gpt4 key购买 nike

我有一个现有的 StringBuilder 对象,代码向它附加了一些值和一个分隔符。

我想修改代码以添加逻辑,在附加文本之前,它将检查它是否已存在于 StringBuilder 中。如果没有,它只会追加文本,否则将被忽略。

这样做的最佳方法是什么?我需要将对象更改为 string 类型吗?我需要不会影响性能的最佳方法。

public static string BuildUniqueIDList(context RequestContext)
{
string rtnvalue = string.Empty;
try
{
StringBuilder strUIDList = new StringBuilder(100);
for (int iCntr = 0; iCntr < RequestContext.accounts.Length; iCntr++)
{
if (iCntr > 0)
{
strUIDList.Append(",");
}

// need to do somthing like:
// strUIDList.Contains(RequestContext.accounts[iCntr].uniqueid) then continue
// otherwise append
strUIDList.Append(RequestContext.accounts[iCntr].uniqueid);
}
rtnvalue = strUIDList.ToString();
}
catch (Exception e)
{
throw;
}
return rtnvalue;
}

我不确定这样的东西是否有效:

if (!strUIDList.ToString().Contains(RequestContext.accounts[iCntr].uniqueid.ToString()))

最佳答案

我个人会使用:

return string.Join(",", RequestContext.accounts
.Select(x => x.uniqueid)
.Distinct());

无需显式循环,手动使用 StringBuilder等等...只需以声明的方式全部表达 :)

(如果您不使用 .NET 4,您需要在最后调用 ToArray(),这显然会稍微降低效率……但我怀疑它会成为您应用程序的瓶颈。)

编辑:好的,对于非 LINQ 解决方案...如果大小合理小我只是为了:

// First create a list of unique elements
List<string> ids = new List<string>();
foreach (var account in RequestContext.accounts)
{
string id = account.uniqueid;
if (ids.Contains(id))
{
ids.Add(id);
}
}

// Then convert it into a string.
// You could use string.Join(",", ids.ToArray()) here instead.
StringBuilder builder = new StringBuilder();
foreach (string id in ids)
{
builder.Append(id);
builder.Append(",");
}
if (builder.Length > 0)
{
builder.Length--; // Chop off the trailing comma
}
return builder.ToString();

如果你有一个字符串集合,你可以使用Dictionary<string, string>作为一种假货 HashSet<string> .

关于c# - 在 C# 中,检查 stringbuilder 是否包含子字符串的最佳方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5119423/

29 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com