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

时间:2011-02-25 16:01:33

标签: c# string contains stringbuilder

我有一个现有的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;
}

我不确定是否会有效率: if(!strUIDList.ToString()。Contains(RequestContext.accounts [iCntr] .uniqueid.ToString()))

1 个答案:

答案 0 :(得分:7)

我个人会用:

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>