2011-02-25 164 views
9

我有一个现有的StringBuilder对象,代码附加了一些值和分隔符。现在我想修改代码来添加前面添加文本的逻辑,我想检查它是否真的存在于字符串生成器变量中?如果不是,则只能追加否则忽略。最好的办法是什么?我是否需要将对象更改为字符串类型?需要一种不会影响性能的最佳方法。在C#中,检查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; 
} 

我不知道,如果有喜欢的东西将是有效的: 如果(!strUIDList.ToString()包含(RequestContext.accounts [iCntr] .uniqueid.ToString()))

回答

8

个人我会用:

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>

+0

我的不好,我应该提到它,我可以做到这一点没有LINQ?在.net 2.0中? – 2011-02-25 16:11:27

+0

@ user465876:你可以,但是我个人认为LINQBridge是LINQ的,所以LINQ是非常有用的,它值得你抓住backport。 – 2011-02-25 16:12:54

+0

乔恩,谢谢你的提示。很快我们将转向3.5,然后我将有限地使用LINQ到最大值。但就时间而言,我需要坚持非LINQ解决方案:(如果你不介意,你能告诉我如何在没有LINQ/LINQBridge的2.0中做到这一点。 – 2011-02-25 16:35:11

相关问题