【问题标题】:In C#, best way to check if stringbuilder contains a substring在 C# 中,检查 stringbuilder 是否包含子字符串的最佳方法
【发布时间】:2011-07-04 09:57:45
【问题描述】:

我有一个现有的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()))

【问题讨论】:

    标签: c# string contains stringbuilder


    【解决方案1】:

    我个人会使用:

    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&lt;string, string&gt;作为一种假HashSet&lt;string&gt;

    【讨论】:

    • 我的错,我应该提到它,我可以在没有 LINQ 的情况下这样做吗?在 .net 2.0 中?
    • @user465876:你可以,但我个人会使用 LINQBridge 来代替...... LINQ非常很有用,值得使用 backport。
    • 乔恩,谢谢你的提示。很快我们将迁移到 3.5,然后我会毫不犹豫地最大限度地使用 LINQ。但就目前而言,我需要坚持非 LINQ 解决方案 :( 如果你不介意,你能告诉我如何在没有 LINQ/LINQBridge 的 2.0 中做到这一点。
    • @user465876:好的,我已经为 .NET 2 添加了替代方案。
    • 感谢乔恩。这真的很有帮助。我会记住 LINQ。
    猜你喜欢
    • 1970-01-01
    • 2021-10-12
    • 2021-12-20
    • 1970-01-01
    • 1970-01-01
    • 2011-07-14
    • 2014-12-20
    • 2012-06-15
    • 1970-01-01
    相关资源
    最近更新 更多