본문 바로가기

.NET/C#

리스트 문자를 콤마로 묶는 코드 작성 | ChatGPT

728x90
반응형

구분된 문자열에 저장 방법

주어진 리스트 요소를 문자열로 묶어서 쉼표로 구분된 문자열에 저장하려면 다음과 같이 할 수 있다.

예시

using System;
using System.Collections.Generic;

class Program
{
    static void Main()
    {
        List<int> list = new List<int> { 4, 5, 6, 7, 8 };
        string result = string.Join(",", list);
        
        Console.WriteLine(result); // 결과 출력
    }
}

string.Join 사용

위의 코드에서 string.Join 메서드를 사용하여 리스트 요소를 쉼표로 구분된 하나의 문자열로 합칩니다. 그런 다음 result 에 해당 문자열이 저장됩니다. 위의 코드를 실행하면 result 에 "4,5,6,7,8" 문자열이 저장되고 결과가 출력됩니다.

출처 | ChatGPT

728x90
반응형