2011-02-25 165 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

相關問題