Convertir lista en una cadena separada por comas


158

Mi código es el siguiente:

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

Salida: 1,2,3,4,5

¿Cuál es la forma más simple de convertirlo List<uint>en una cadena separada por comas?


9
String.Joines todo lo que necesitas.
asawyer

9
var csvString = String.Join(",", lst);Deberías hacerlo.
Mithrandir

2
Para cualquiera que quiera volver a abrir esto, si no está demasiado localizado, es un duplicado: stackoverflow.com/questions/799446/…
Tim Schmelter

Respuestas:


320

¡Disfrutar!

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

Primer parámetro: ","
segundo parámetro:new List<uint> { 1, 2, 3, 4, 5 })

String.Join tomará una lista como el segundo parámetro y unirá todos los elementos usando la cadena pasada como primer parámetro en una sola cadena.


11
En .NET 3.5 y versiones posteriores, debe convertir explícitamente su lista a matriz lst.ToArray(), ya que todavía no hay una sobrecarga directa.
Anton


25

Utilizando String.Join

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

Utilizando Linq Aggregation

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

1
Tengo una lista de tipo int32. cuando uso la función de agregado que mencionó, dice "No se puede convertir la expresión lambda al tipo de delegado 'System.Func <int, int, int>' porque algunos de los tipos de retorno en el bloque no son implícitamente convertibles al tipo de retorno de delegado" y "No se puede convertir implícitamente el tipo 'string' a 'int'"
Hari

1
@Hari Debe convertirlo a valores de cadena antes de agregar a cadena. Entonces puede hacer algo como esto: list.Select (x => string.Format ("{0}: {1}", x.Key, x.Value)). Aggregate ((a, x) => a + " , "+ x);
apuesta el

11

Si tienes una colección de entradas:

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

Puede usar string.Joinpara obtener una cadena:

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

¡Disfrutar!


9

Sigue esto:

       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

           }

Utilicé en MVC Razor View para evaluar e imprimir todos los roles separados por comas.


3

Puede usar String.Join para esto si está usando .NET framework> 4.0.

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

2

Puede consultar el siguiente ejemplo para obtener una matriz de cadenas separadas por comas de la lista.

Ejemplo:

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

Tratar

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

HTH


1

Podemos intentar así separar las entradas de la lista por comas

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

Convierta una lista de cadenas en cadenas separadas por comas C #


0

también puede anular ToString () si el elemento de su lista tiene más de una cadena

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

    }

}

para obtener la cadena 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)

Este es el resultado: sprots, noticias


0

Puede separar las entidades de lista con una coma como esta:

//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);
Al usar nuestro sitio, usted reconoce que ha leído y comprende nuestra Política de Cookies y Política de Privacidad.
Licensed under cc by-sa 3.0 with attribution required.