Pregunta

My values come from ComboBox:

2|722|742|762|77

I delete unnecessary characters as follows:

foreach (var item in checkListBox)
{
    string[] list = item.Split(
        new string[] { "2|" },
        StringSplitOptions.RemoveEmptyEntries);
}

My list values result:

"72"
"74"
"76"
"77"

My question is:

how can I get all of the above values in 1 row (next to each other) separated by comma like this:

72,74,76,77

?

¿Fue útil?

Solución 3

How about

var result = string.Join(",", item.Split(new string[] { "2|" }, StringSplitOptions.RemoveEmptyEntries));

Otros consejos

It sounds like you just want string.Join:

string commaSeparated = string.Join(",", list);

(Note that this is not part of LINQ - it's not the same kind of "join" as for joining multiple sequences. It's joining several strings together with a separator.)

While you can do this in a single statement as per the currently accepted answer, I'd personally consider leaving your existing statement and having this as a separate step. It makes the code easier to both read and debug.

String.Join(",",list);​​​​​​​​​​​​​​​​​​​​​​​​​

Though: a) This is not Linq. b) As is mentioned in another answer here - It would be simpler in this case to use Replace.

Using Linq:

list.Select(s => s + ",").Aggregate((s, q) => s + q).TrimEnd(',');

Just use Replace directly:

string input = "2|722|742|762|77";
var result = input.Replace("2|",",").Trim(',');

As noted in the other answers, string.Join is what should be used here. If you'd however insist on LINQ:

var result = list
    .Skip(1)
    .Aggregate(
        list.FirstOrDefault() ?? string.Empty,
        (total, current) => total + "," + current);
Licenciado bajo: CC-BY-SA con atribución
No afiliado a StackOverflow
scroll top