List of string chuyển thành comma-separated string dùng built-in string.Join extension method.
string.Join(",", list);
Chuyển đổi này hữu ích khi thu thập list data (ví dụ: checkbox selected data) từ user, chuyển thành comma-separated string để query database xử lý tiếp.
Ví dụ cơ bản
using System;
using System.Collections.Generic;
namespace DemoApplication
{
public class Program
{
static void Main(string[] args)
{
List fruitsList = new List { "banana", "apple", "mango" };
string fruits = string.Join(",", fruitsList);
Console.WriteLine(fruits);
Console.ReadLine();
}
}
}
Kết quả
banana,apple,mango
Tương tự, property trong list of complex objects cũng chuyển thành comma-separated string:
Ví dụ complex object
using System;
using System.Collections.Generic;
using System.Linq;
namespace DemoApplication
{
public class Program
{
static void Main(string[] args)
{
var studentsList = new List
{
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; }
}
}
Kết quả
John,Jack