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

Sri*_*ddy 10 c# string stringbuilder contains

我有一个现有的StringBuilder对象,代码附加一些值和一个分隔符.现在我想修改代码以添加逻辑,在附加我要检查的文本之前是否确实存在于字符串生成器变量中?如果没有,那么只有附加否则忽略.这样做的最佳方法是什么?我是否需要将对象更改为字符串类型?需要一种不会妨碍性能的最佳方法.

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 other wise append
            strUIDList.Append(RequestContext.accounts[iCntr].uniqueid);
        }
        rtnvalue = strUIDList.ToString();
    }
    catch (Exception e)
    {
        throw;
    }
    return rtnvalue;
}
Run Code Online (Sandbox Code Playgroud)

我不确定是否有类似的东西会有效:if(!strUIDList.ToString().Contains(RequestContext.accounts [iCntr] .uniqueid.ToString()))

Jon*_*eet 7

我个人会用:

return string.Join(",", RequestContext.accounts
                                      .Select(x => x.uniqueid)
                                      .Distinct());
Run Code Online (Sandbox Code Playgroud)

无需显式循环,手动使用StringBuilder等...只是以声明方式表达所有:)

(ToArray()如果你不使用.NET 4,你最后需要打电话,这显然会降低效率......但我怀疑它会成为你应用的瓶颈.)

编辑:好的,对于非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();
Run Code Online (Sandbox Code Playgroud)

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