【问题标题】:Comma "izing" a list of items逗号“化”项目列表
【发布时间】:2010-09-26 23:33:38
【问题描述】:

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

【问题讨论】:

    标签: .net string vb.net


    【解决方案1】:
    Dim Result As String
    Dim Items As New List(Of String)
    Items.Add("Hello")
    Items.Add("World")
    
    Result = String.Join(",", Items)
    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
    

    以上内容真的很老了。今天,我会像这样清除空字符串:

    Dim Result As String = String.Join("," Items.Where(Function(i) Not String.IsNullOrWhitespace(i)))
    

    【讨论】:

      【解决方案2】:

      解决方案使用StringBuilderConcat 方法吗?

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

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

      更多详情请参阅my very similar question

      【讨论】:

        【解决方案3】:

        像这样:

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

        【讨论】:

          【解决方案4】:

          从 String.Join 答案开始,忽略空/空字符串(如果您使用的是 .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)
          

          【讨论】:

          • 我喜欢它。我什至没有想过为此使用 linq...不能 linq 做什么?
          【解决方案5】:

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

          【讨论】:

            【解决方案6】:

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

            伪代码:

            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
            

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

            【讨论】:

              【解决方案7】:

              或者你可以这样做:

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

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

              【讨论】:

                【解决方案8】:

                您是否相信 .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();
                        }
                

                【讨论】:

                  【解决方案9】:

                  感谢所有回复。

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

                  所以我选择了一些效果

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

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

                  再次感谢大家的意见。

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

                  【讨论】:

                    【解决方案10】:
                    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

                    【讨论】:

                      猜你喜欢
                      • 1970-01-01
                      • 2021-12-31
                      • 1970-01-01
                      • 1970-01-01
                      • 1970-01-01
                      • 1970-01-01
                      • 2019-09-24
                      • 2012-04-17
                      • 2016-11-09
                      相关资源
                      最近更新 更多