如何在C#中用一個字串列表建立一個逗號分隔字串?


可以使用內建的string.Join擴充套件方法將字串列表轉換為逗號分隔的字串。

string.Join("," , list);

當我們從使用者處收集一份資料列表(例如:複選框選中資料)並將其轉換為逗號分隔的字串並查詢資料庫以進一步處理時,這種型別的轉換非常有用。

示例

 線上演示

using System;
using System.Collections.Generic;
namespace DemoApplication {
   public class Program {
      static void Main(string[] args) {
         List<string> fruitsList = new List<string> {
            "banana",
            "apple",
            "mango"
         };
         string fruits = string.Join(",", fruitsList);
         Console.WriteLine(fruits);
         Console.ReadLine();
      }
   }
}

輸出

以上程式碼的輸出是

banana,apple,mango

類似地,複雜的\物件列表中的屬性也可以轉換為逗號分隔的字串,如下所示。

示例

 線上演示

using System;
using System.Collections.Generic;
using System.Linq;
namespace DemoApplication {
   public class Program {
      static void Main(string[] args) {
         var studentsList = new List<Student> {
            new Student {
               Id = 1,
               Name = "John"
            },
            new Student {
               Id = 2,
               Name = "Jack"
            }
         };
         string students = string.Join(",", studentsList.Select(student => student.Name));
         Console.WriteLine(students);
         Console.ReadLine();
      }
   }
   public class Student {
      public int Id { get; set; }
      public string Name { get; set; }
   }
}

輸出

以上程式碼的輸出是

John,Jack

更新時間:08-Aug-2020

11K+瀏覽

開啟你的 職業生涯

完成課程,獲得認證

開始學習
廣告