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

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

public static string BuildUniqueIDList(context RequestContext) { string rtnvalue = string.Empty; try { StringBuilder strUIDList = new StringBuilder(100); for (int iCntr = 0; 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()))

我个人会用:

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

不需要显式循环,手动使用StringBuilder等…只是声明地表达它:)

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

编辑:好的,对于非LINQ解决方案……如果尺寸相当小,我只是为了:

 // First create a list of unique elements List ids = new List(); 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作为一种假HashSet