可以使用内置的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