รายการสตริงสามารถแปลงเป็นสตริงที่คั่นด้วยเครื่องหมายจุลภาคได้โดยใช้วิธีการขยาย 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