Share via


Split.join with foreach loop .Net 4.5

Question

Thursday, May 16, 2019 7:56 AM

I am trying to create a comma separated string with foreach loop and split. join, but I only get the last value in a string. Here is my code:

 string columns = string.Empty;
            foreach (var item in obj.Checkboxes)
            {
                if (item.IsChecked)
                {
                    //columns = sb.Append(item.Value + ",").ToString();
                    columns = string.Join(",", item.Value);
                }
            }

All replies (3)

Friday, May 17, 2019 2:52 AM âś…Answered

Hi Ridzi,

but I only get the last value in a string.

Because your columns is string.Empty,it can't store array.

You could code like:

         StringBuilder columns  = new StringBuilder();
         foreach (var item in obj.Checkboxes)
            {
                if (item.IsChecked)
                {
                    columns.Append(item.Value + ",").ToString();

                }
            }

Best Regards.

Yuki Tao


Thursday, May 16, 2019 8:11 AM

Hi,

You assign a new value to columns again and again in each loop so it is expected (seems a confusion with your previous StringBuilder.Append which append the value to the existing value).

It seems you want something such as (needs using System.Linq) :

var columns=String.Join(",",obj.Chekboxes.Where(o=>o.IsChecked).Select(o=>o.Value.ToString())); 

ie you extract the information you want to concatenate (make sure it is a string) and then you use String.Join on this list to concatenate all values...

See /en-us/dotnet/csharp/programming-guide/concepts/linq/linq-to-objects


Friday, May 17, 2019 2:56 AM

Change it to:

 columns += string.Join(",", item.Value);