문자열 목록은 내장된 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