在C#中,检查stringbuilder是否包含子字符串的最佳方法 [英] In C#, best way to check if stringbuilder contains a substring
问题描述
我有一个现有的 StringBuilder
对象,代码向其附加了一些值和定界符。
I have an existing StringBuilder
object, the code appends some values and a delimiter to it.
I想要修改代码以添加逻辑,即在添加文本之前,它将检查 StringBuilder
中是否已经存在。如果没有,则仅会附加文本,否则它将被忽略。
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.
这样做的最佳方法是什么?我是否需要将对象更改为 string
类型?我需要一种不会影响性能的最佳方法。
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()))
推荐答案
我个人会使用:
return string.Join(",", RequestContext.accounts
.Select(x => x.uniqueid)
.Distinct());
无需显式循环,手动使用 StringBuilder
等...只是声明式地表达所有内容:)
No need to loop explicitly, manually use a StringBuilder
etc... just express it all declaratively :)
(您需要调用 ToArray()
最后,如果您不使用.NET 4,这显然会降低效率...但是我怀疑它会成为您应用程序的瓶颈。)
(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.)
编辑:好吧,对于非LINQ解决方案...如果大小是合理小,我只想这样做:
Okay, for a non-LINQ solution... if the size is reasonably small I'd just for for:
// 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();
如果可以有 large 个字符串集合,则可以使用 Dictionary< string,string>
作为一种伪造的 HashSet< string>
。
If you could have a large collection of strings, you might use Dictionary<string, string>
as a sort of fake HashSet<string>
.
这篇关于在C#中,检查stringbuilder是否包含子字符串的最佳方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!