Converti elenco in stringa separata da virgola


158

Il mio codice è il seguente:

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);
}

Produzione: 1,2,3,4,5

Qual è il modo più semplice per convertire la List<uint>stringa in una stringa separata da virgola?


9
String.Joiné tutto quello di cui hai bisogno.
asawyer,

9
var csvString = String.Join(",", lst);dovrebbe farlo.
Mithrandir,

2
Per chi vuole riaprire questo, se non è troppo localizzata si tratta di un duplicato: stackoverflow.com/questions/799446/...
Tim Schmelter

Risposte:


320

Godere!

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

Primo parametro: ","
Secondo parametro:new List<uint> { 1, 2, 3, 4, 5 })

String.Join prenderà un elenco come secondo parametro e unirà tutti gli elementi usando la stringa passata come primo parametro in una singola stringa.


11
In .NET 3.5 e versioni precedenti è necessario convertire esplicitamente l'elenco in array con lst.ToArray(), poiché non vi è ancora un sovraccarico diretto.
Anton,


25

utilizzando String.Join

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

utilizzando Linq Aggregation

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

1
Ho un elenco di tipo int32. quando uso la funzione aggregata che hai citato, dice "Impossibile convertire l'espressione lambda nel tipo delegato 'System.Func <int, int, int>' perché alcuni dei tipi restituiti nel blocco non sono implicitamente convertibili nel tipo restituito delegato" e "Impossibile convertire implicitamente il tipo 'stringa' in 'int'"
Hari

1
@Hari È necessario convertirlo in valori stringa prima di eseguire l'aggregazione in stringa. Quindi puoi fare qualcosa del genere: list.Select (x => string.Format ("{0}: {1}", x.Key, x.Value)). Aggregate ((a, x) => a + " , "+ x);
scommesse

11

Se hai una raccolta di ints:

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

Puoi usare string.Joinper ottenere una stringa:

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

Godere!


9

Segui questo:

       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

           }

Ho usato in MVC Razor View per valutare e stampare tutti i ruoli separati da virgole.


3

È possibile utilizzare String.Join per questo se si utilizza .NET framework> 4.0.

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

2

È possibile fare riferimento all'esempio seguente per ottenere un array di stringhe separato da virgole dall'elenco.

Esempio:

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

Provare

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

HTH


1

Possiamo provare in questo modo a separare le entità elenco con una virgola

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


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);}

Converti un elenco di stringhe in stringhe separate da virgole C #


0

puoi anche sostituire ToString () se la tua voce di elenco ha più di una stringa

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);

    }

}

per ottenere una stringa 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)

Questo è l'output: sprots, notizie


0

Puoi separare le entità dell'elenco con una virgola come questa:

//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);
Utilizzando il nostro sito, riconosci di aver letto e compreso le nostre Informativa sui cookie e Informativa sulla privacy.
Licensed under cc by-sa 3.0 with attribution required.