쉼표로 구분 된 문자열로 목록 변환


158

내 코드는 다음과 같습니다.

public void ReadListItem()
{
     List<uint> lst = new List<uint>() { 1, 2, 3, 4, 5 };
     string str = string.Empty;
     foreach (var item in lst)
         str = str + item + ",";

     str = str.Remove(str.Length - 1);
     Console.WriteLine(str);
}

산출: 1,2,3,4,5

List<uint>쉼표로 구분 된 문자열로 변환하는 가장 간단한 방법은 무엇입니까 ?


8
String.Join당신이 필요한 전부입니다.
asawyer

8
var csvString = String.Join(",", lst);해야합니다.
Mithrandir

2
: 원하는 사람이 재개하려면 너무 지역화되어 있지 않은 경우, 그것은 중복의 stackoverflow.com/questions/799446/...
팀 Schmelter

답변:


319

즐겨!

Console.WriteLine(String.Join(",", new List<uint> { 1, 2, 3, 4, 5 }));

첫 번째 매개 변수 : ","
두 번째 매개 변수 :new List<uint> { 1, 2, 3, 4, 5 })

String.Join 은 두 번째 매개 변수로 목록을 가져 와서 첫 번째 매개 변수로 전달 된 문자열을 사용하여 모든 요소를 ​​단일 문자열로 결합합니다.


11
.NET 3.5 이하 lst.ToArray()에서는 아직 직접 과부하가 없으므로을 사용하여 목록을 명시 적으로 배열로 변환해야합니다 .
Anton


25

사용 String.Join

string.Join<string>(",", lst );

사용 Linq Aggregation

lst .Aggregate((a, x) => a + "," + x);

1
int32 유형의 목록이 있습니다. 언급 한 집계 함수를 사용하면 "블록의 일부 반환 유형이 대리자 반환 유형으로 암시 적으로 변환 할 수 없으므로 람다 식을 'System.Func <int, int, int>'대리자 유형으로 변환 할 수 없습니다"라고 표시됩니다. "암시 적으로 'string'유형을 'int'로 변환 할 수 없음"
Hari

1
@Hari 문자열로 집계하기 전에 문자열 값으로 변환해야합니다. 따라서 다음과 같이 할 수 있습니다 : list.Select (x => string.Format ( "{0} : {1}", x.Key, x.Value)). Aggregate ((a, x) => a + " , "+ x);
내기

11

정수 컬렉션이있는 경우 :

List<int> customerIds= new List<int>() { 1,2,3,3,4,5,6,7,8,9 };  

string.Join문자열을 얻는 데 사용할 수 있습니다 .

var result = String.Join(",", customerIds);

즐겨!


9

이것을 따르십시오 :

       List<string> name = new List<string>();

        name.Add("Latif");
        name.Add("Ram");
        name.Add("Adam");
        string nameOfString = (string.Join(",", name.Select(x => x.ToString()).ToArray()));

4
          @{  var result = string.Join(",", @user.UserRoles.Select(x => x.Role.RoleName));
              @result

           }

MVC Razor View에서 쉼표로 구분 된 모든 역할을 평가하고 인쇄하는 데 사용했습니다.



2

목록에서 쉼표로 구분 된 문자열 배열을 가져 오려면 아래 예를 참조하십시오.

예:

List<string> testList= new List<string>();
testList.Add("Apple"); // Add string 1
testList.Add("Banana"); // 2
testList.Add("Mango"); // 3
testList.Add("Blue Berry"); // 4
testList.Add("Water Melon"); // 5

string JoinDataString = string.Join(",", testList.ToArray());

1

시험

Console.WriteLine((string.Join(",", lst.Select(x=>x.ToString()).ToArray())));

HTH


1

쉼표로 목록 엔터를 구분하기 위해 이와 같이 시도 할 수 있습니다.

string stations = 
haul.Routes != null && haul.Routes.Count > 0 ?String.Join(",",haul.Routes.Select(y => 
y.RouteCode).ToList()) : string.Empty;

0

Joiner라는 유틸리티 클래스가있는 google-collections.jar을 사용할 수 있습니다.

 String commaSepString=Joiner.on(",").join(lst);

또는

join이라는 함수가있는 StringUtils 클래스를 사용할 수 있습니다 .StringUtils 클래스를 사용하려면 common-lang3.jar을 사용해야합니다.

String commaSepString=StringUtils.join(lst, ',');

참조를 위해이 링크를 참조하십시오 http://techno-terminal.blogspot.in/2015/08/convert-collection-into-comma-separated.html


0
static void Main(string[] args){          
List<string> listStrings = new List<string>() { "C#", "Asp.Net", "SQL Server", "PHP", "Angular" };  
string CommaSeparateString = GenerateCommaSeparateStringFromList(listStrings);  
Console.Write(CommaSeparateString);  
Console.ReadKey();}
private static string GenerateCommaSeparateStringFromList(List<string> listStrings){return String.Join(",", listStrings);}

문자열 목록을 쉼표로 구분 된 문자열 C #으로 변환


0

목록 항목에 둘 이상의 문자열이있는 경우 ToString ()을 재정의 할 수도 있습니다.

public class ListItem
{

    public string string1 { get; set; }

    public string string2 { get; set; }

    public string string3 { get; set; }

    public override string ToString()
    {
        return string.Join(
        ","
        , string1 
        , string2 
        , string3);

    }

}

CSV 문자열을 얻으려면 :

ListItem item = new ListItem();
item.string1 = "string1";
item.string2 = "string2";
item.string3 = "string3";

List<ListItem> list = new List<ListItem>();
list.Add(item);

string strinCSV = (string.Join("\n", list.Select(x => x.ToString()).ToArray()));

0
categories = ['sprots', 'news'];
categoriesList = ", ".join(categories)
print(categoriesList)

이것은 출력입니다 : sprots, news


0

다음과 같이 쉼표로 목록 엔터티를 구분할 수 있습니다.

//phones is a list of PhoneModel
var phoneNumbers = phones.Select(m => m.PhoneNumber)    
                    .Aggregate(new StringBuilder(),
                        (current, next) => current.Append(next).Append(" , ")).ToString();

// Remove the trailing comma and space
if (phoneNumbers.Length > 1)
    phoneNumbers = phoneNumbers.Remove(phoneNumbers.Length - 2, 2);
당사 사이트를 사용함과 동시에 당사의 쿠키 정책개인정보 보호정책을 읽고 이해하였음을 인정하는 것으로 간주합니다.
Licensed under cc by-sa 3.0 with attribution required.