逗号“izing”项目列表

时间:2008-12-15 14:38:12

标签: c# .net 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)

10 个答案:

答案 0 :(得分: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)

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

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

答案 1 :(得分:10)

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

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

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

有关详细信息,请参阅my very similar question

答案 2 :(得分:5)

像这样:

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

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

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

我工具箱中最受欢迎的自定义聚合函数。我每天都用它:

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();
    }
}

答案 3 :(得分:5)

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

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)

答案 4 :(得分:2)

如果你没有 使用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

答案 5 :(得分:1)

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

伪代码:

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

编辑:我喜欢第二种方式的原因是每个项目都独立存在。使用第一种方法,如果您稍后修改了逻辑,以便后续项目可能不会被添加,那么可以在字符串末尾添加一个逗号逗号,除非您还在以前的项目更聪明,这是愚蠢的。

答案 6 :(得分:1)

或者你可以这样做:

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

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

答案 7 :(得分:1)

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

public static string ListToCsv<T>(List<T> list)
        {
            CommaDelimitedStringCollection commaStr = new CommaDelimitedStringCollection();

            list.ForEach(delegate(T item)
            {
                commaStr.Add(item.ToString());
            });


            return commaStr.ToString();
        }

答案 8 :(得分:0)

感谢所有回复。

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

所以我选择了一些影响

的东西

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

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

再次感谢大家的投入。

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

答案 9 :(得分:0)

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