In C#, best way to check if stringbuilder contains a substring

生来就可爱ヽ(ⅴ<●) 提交于 2019-12-05 01:22:57

Personally I would use:

return string.Join(",", RequestContext.accounts
                                      .Select(x => x.uniqueid)
                                      .Distinct());

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:

// 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();

If you could have a large collection of strings, you might use Dictionary<string, string> as a sort of fake HashSet<string>.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!