1

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

?

5 Answers 5

7

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.

Sign up to request clarification or add additional context in comments.

Comments

3
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(',');

Comments

2

How about

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

Comments

1

Just use Replace directly:

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

Comments

0

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.