【问题标题】:How to add commas between array members, etc?如何在数组成员之间添加逗号等?
【发布时间】:2023-04-05 02:56:01
【问题描述】:

我只是在每个单词旁边添加逗号:

 foreach (DataRow row in ds.Tables[0].Rows)
 {                {
    sqlIn += row["personId"] + ", ";
 }

然后我删除最后一个不需要的逗号:

 sqlIn = sqlIn.TrimEnd(' ', ',');

我感觉就像在经典的 ASP 时代。我的工作是否有任何 C# 版本?

【问题讨论】:

  • 为什么不使用列表或集合并将所有结果添加到其中?

标签: c#


【解决方案1】:

使用String.Join

String.Join(", ", ds.Tables[0].Rows.Select(r => r["personId"].ToString()));

【讨论】:

    【解决方案2】:

    Bas B 答案的进一步正确的语法是

     string s = String.Join(", ", ds.Tables[0].Select().Select(r => r["personID"].ToString()));
    

    这是工作证明

    using System;
    using System.Linq;
    using System.Data.Linq;
    using System.Data;
    
    
        namespace ConsoleApplication5
        {
          class Program
          {
    
            static void Main(string[] args)
            {
              DataSet ds = new DataSet();
    
              DataTable dt = new DataTable();
              ds.Tables.Add(dt);
              string col = "personId";
              dt.Columns.Add(col, typeof(int));
    
              dt.Rows.Add(1);
              dt.Rows.Add(2);
    
              string s = String.Join(", ", ds.Tables[0].Select().Select(r => r["personID"].ToString()));
    
              Console.WriteLine(s);
              Console.ReadLine();
    
            }
          }
    
        }
    

    输出将是

    1, 2
    

    【讨论】:

      【解决方案3】:

      使用String.Join 方法 - 请参阅http://msdn.microsoft.com/en-us/library/system.string.join.aspx 了解可能的重载。

      【讨论】:

        【解决方案4】:

        您希望它转换为 CSV。

        您可以使用以下String.Join 重载:

        (方法一) String.Join 将列值转换为数组后或

        (方法二) 可以使用String.Join重载Join(Of T)(String, IEnumerable(Of T)),Select Extension方法会返回String类型的IEnumerable值。

        方法一:

        String.Join(",", (From row In ds.Tables[0].Rows.AsEnumerable Select row["personId")).ToArray)
        

        方法二:

        String.Join(", ", ds.Tables[0].Rows.Select(row => row["personId"].ToString()));
        

        请关注此 SO 线程以供参考:Convert single column of a DataTable to CSV

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 2018-01-12
          • 2020-10-27
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2019-10-16
          • 2016-07-05
          相关资源
          最近更新 更多