逗号"izing"项目列表

use*_*826 13 .net c# vb.net string

给定一个字符串列表,将这些字符串连接成逗号分隔列表的最佳方法是什么,最后没有逗号.(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)
Run Code Online (Sandbox Code Playgroud)

Joe*_*orn 32

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)
Run Code Online (Sandbox Code Playgroud)

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

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
Run Code Online (Sandbox Code Playgroud)


Dan*_*nov 10

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

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

string result = String.Join(",", items.ToArray());
Run Code Online (Sandbox Code Playgroud)

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


Pet*_*ery 5

像这样:

lstItems.ToConcatenatedString(s => s, ", ")
Run Code Online (Sandbox Code Playgroud)

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

lstItems
    .Where(s => s.Length > 0)
    .ToConcatenatedString(s => s, ", ")
Run Code Online (Sandbox Code Playgroud)

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

public static class EnumerableExtensions
{

    /// <summary>
    /// Creates a string from the sequence by concatenating the result
    /// of the specified string selector function for each element.
    /// </summary>
    public static string ToConcatenatedString<T>(
        this IEnumerable<T> source,
        Func<T, string> stringSelector)
    {
        return EnumerableExtensions.ToConcatenatedString(source, stringSelector, String.Empty);
    }

    /// <summary>
    /// Creates a string from the sequence by concatenating the result
    /// of the specified string selector function for each element.
    /// </summary>
    /// <param name="separator">The string which separates each concatenated item.</param>
    public static string ToConcatenatedString<T>(
        this IEnumerable<T> source,
        Func<T, string> 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();
    }
}
Run Code Online (Sandbox Code Playgroud)


Pau*_*ney 5

继续从String.Join回答,忽略null/empty字符串(如果你使用的是.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)
Run Code Online (Sandbox Code Playgroud)