Convert List<int> to delimited string list [duplicate]
Asked Answered
B

5

68

Possible Duplicate:
most elegant way to return a string from List<int>

I'm not sure the easiest way to do this. I simply want to add a ; between each value and spit it out as one string. I don't see that you can do this with ToString(). I'd have to loop through and create a stringbuilder and append & add a ";".

Billiot answered 28/6, 2010 at 19:11 Comment(5)
sorry that is an List<int> not List<string>Billiot
I need to convert a List<string> to a delmited string. So "123;343;222"Billiot
@coffeeaddict: It's OK to edit your original question. That's better than hoping people will read all the details in the comments.Camail
I think this is probably an exact duplicate of #1334572Diapositive
Except that there is now a better (.NET 4.0 only) answer.Dulsea
D
143

UPDATED to use List<int> instead of List<string>

Use string.Join:

List<int> data = ..;
var result = string.Join(";", data); // (.NET 4.0+)
var result = string.Join(";", data.Select(x => x.ToString()).ToArray()); // (.NET 3.5)
Dulsea answered 28/6, 2010 at 19:12 Comment(5)
sorry I have changed the question, my mistakeBilliot
I've updated the answer to match.Dulsea
+1 for .Net 4 enumerable string.JoinAntwanantwerp
interesting. I had also tried myIntList.ToString().ToArray() but must be doing something wrongBilliot
var result = data.ConvertAll(c=>c.ToString()); where data is List<int>Accoucheur
A
8
string.Join(";", myList.ToArray());
Arthurarthurian answered 28/6, 2010 at 19:12 Comment(0)
C
4

Just use the join

string combinedString = String.Join(";", arrayName);
Currie answered 28/6, 2010 at 19:13 Comment(0)
S
3
List<String> list = new List<String>() { "A", "B", "C", "D", "E" };
String joindString1 = String.Join(";", list.ToArray());
String joindString2 = list.Aggregate((s1, s2) => s1 + ";" + s2);
Spherical answered 28/6, 2010 at 19:19 Comment(0)
A
2

You can also use Enumerable.Aggregate which can give extra flexibility.

var data = new List<int> { 1,2,3 };
var sb = new StringBuilder(100);

// do some other stuff with sb

sb = data.Aggregate(sb, (b, d) => b.Append(d).Append(';'));
if( data.Count > 0 ) sb.Length--;

//do some more stuff with sb

var str = sb.ToString();
Agnusago answered 28/6, 2010 at 21:40 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.