逗号“izing”一个项目列表

给定一个字符串列表,将这些字符串连接成逗号分隔列表的最佳方法是什么,最后没有逗号。 (VB.NET或C#)(使用StringBuilder或String Concat。)

Dim strResult As String = "" Dim lstItems As New List(Of String) lstItems.Add("Hello") lstItems.Add("World") For Each strItem As String In lstItems If strResult.Length > 0 Then strResult = strResult & ", " End If strResult = strResult & strItem Next MessageBox.Show(strResult) 

 Dim Result As String Dim Items As New List(Of String) Items.Add("Hello") Items.Add("World") Result = String.Join(",", Items.ToArray()) MessageBox.Show(Result) 

如果您真的关心空字符串,请使用此连接函数:

 Function Join(ByVal delimiter As String, ByVal items As IEnumerable(Of String), Optional ByVal IgnoreEmptyEntries As Boolean = True) As String Dim delim As String = "" Dim result As New Text.StringBuilder("") For Each item As String In items If Not IgnoreEmptyEntries OrElse Not String.IsNullOrEmpty(item) Then result.Append(delim).Append(item) delim = delimiter End If Next Return result.ToString() End Function 

解决方案是否必须使用StringBuilderConcat方法?

如果没有,您可以使用静态String.Join方法。 例如(在C#中):

 string result = String.Join(",", items.ToArray()); 

有关详细信息,请参阅我非常相似的问题 。

像这样:

 lstItems.ToConcatenatedString(s => s, ", ") 

如果要在示例中忽略空字符串:

 lstItems .Where(s => s.Length > 0) .ToConcatenatedString(s => s, ", ") 

我工具箱中最流行的自定义聚合函数。 我每天都使用它:

 public static class EnumerableExtensions { ///  /// Creates a string from the sequence by concatenating the result /// of the specified string selector function for each element. ///  public static string ToConcatenatedString( this IEnumerable source, Func stringSelector) { return EnumerableExtensions.ToConcatenatedString(source, stringSelector, String.Empty); } ///  /// Creates a string from the sequence by concatenating the result /// of the specified string selector function for each element. ///  /// The string which separates each concatenated item. public static string ToConcatenatedString( this IEnumerable source, Func stringSelector, string separator) { var b = new StringBuilder(); bool needsSeparator = false; // don't use for first item foreach (var item in source) { if (needsSeparator) b.Append(separator); b.Append(stringSelector(item)); needsSeparator = true; } return b.ToString(); } } 

继续从String.Join回答,忽略null /空字符串(如果你使用的是.NET 3.5),你可以使用一点Linq。 例如

 Dim Result As String Dim Items As New List(Of String) Items.Add("Hello") Items.Add("World") Result = String.Join(",", Items.ToArray().Where(Function(i) Not String.IsNullOrEmpty(i)) MessageBox.Show(Result) 

如果您不必使用StringBuilderConcat方法,您还可以使用:

 using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.IO; using System.Net; using System.Configuration; namespace ConsoleApplication { class Program { static void Main(string[] args) { CommaDelimitedStringCollection commaStr = new CommaDelimitedStringCollection(); string[] itemList = { "Test1", "Test2", "Test3" }; commaStr.AddRange(itemList); Console.WriteLine(commaStr.ToString()); //Outputs Test1,Test2,Test3 Console.ReadLine(); } } } 

这需要引用System.Configuration

有几种方法可以做到这一点,但它们基本上是主题的变体。

伪代码:

 For Each Item In Collection: Add Item To String If Not Last Item, Add Comma 

我喜欢一种更好的方式是这样的:

 For Each Item In Collection: If Not First Item, Add Comma Add Item To String 

编辑:我喜欢第二种方式的原因是每个项目都独立。 使用第一种方法,如果您稍后修改了逻辑,以便后续项目可能不会被添加,您最终可能会在字符串末尾添加一个逗号逗号,除非您还使上一项中的测试更加智能化,这是哑。

或者你可以这样做:

 Separator = "" For Each Item In Collection Add Separator + Item To String Separator = ", " 

通过在第一次迭代中将分隔符设置为空字符串,可以跳过第一个逗号。 如果声明少一个。 这可能会或可能不会更具可读性,具体取决于您习惯使用的内容

您是否相信.NET框架中有一个提供此function的类?

 public static string ListToCsv(List list) { CommaDelimitedStringCollection commaStr = new CommaDelimitedStringCollection(); list.ForEach(delegate(T item) { commaStr.Add(item.ToString()); }); return commaStr.ToString(); } 

感谢所有的回复。

似乎“正确”的答案取决于构建逗号分隔列表的上下文。 我没有一个整洁的项目列表(必须使用一些例子……),但我确实有一个数组,其项目可能会或可能不会添加到逗号分隔列表中,具体取决于各种条件。

所以我选择了一些效果

 strResult = "" strSeparator = "" for i as integer = 0 to arrItems.Length - 1 if arrItems(i) <> "test" and arrItems(i) <> "point" then strResult = strResult & strSeparator & arrItem(i) strSeparator = ", " end if next 

像往常一样,有很多方法可以做到这一点。 我不知道任何一种方法都值得赞扬或推广。 有些在某些情况下更有用,而有些则满足不同情境的要求。

再次感谢大家的投入。

顺便说一句,带有“我的头顶”代码示例的原始post不会过滤零长度项,而是在添加逗号之前等待结果字符串变为大于零的长度。 可能效率不高但我没有测试过。 再次,它是我的头顶。

 Dim strResult As String = "" Dim separator = "," Dim lstItems As New List(Of String) lstItems.Add("Hello") lstItems.Add("World") For Each strItem As String In lstItems strResult = String.Concat(strResult, separator) Next strResult = strResult.TrimEnd(separator.ToCharArray()) MessageBox.Show(strResult) 

想法是使用String.TrimEnd() function