在 C# 中,检查 stringbuilder 是否包含子字符串的最佳方法
我有一个现有的 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()))
I have an existing StringBuilder
object, the code appends some values and a delimiter to it.
I want to modify the code to add the logic that before appending the text, it will check if it already exists in the StringBuilder
. If it does not, only then will it append the text, otherwise it is ignored.
What is the best way to do so? Do I need to change the object to string
type? I need the best approach that will not hamper performance.
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;
}
I am not sure if having something like this will be efficient:
if (!strUIDList.ToString().Contains(RequestContext.accounts[iCntr].uniqueid.ToString()))
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
就我个人而言,我会使用:
不需要显式循环,手动使用
StringBuilder
等...只需以声明方式表达它:)(您需要调用
ToArray()
最后,如果您不使用 .NET 4,这显然会在一定程度上降低效率...但我怀疑它会成为您的应用程序的瓶颈。)编辑:好的,对于非 LINQ 解决方案...如果大小合理小,我只是为了:
如果你可以有大字符串集合,你可以使用
Dictionary< /code> 作为一种假的
HashSet
。Personally I would use:
No need to loop explicitly, manually use a
StringBuilder
etc... just express it all declaratively :)(You'd need to call
ToArray()
at the end if you're not using .NET 4, which would obviously reduce the efficiency somewhat... but I doubt it'll become a bottleneck for your app.)EDIT: Okay, for a non-LINQ solution... if the size is reasonably small I'd just for for:
If you could have a large collection of strings, you might use
Dictionary<string, string>
as a sort of fakeHashSet<string>
.