I Love Stackoverflow
I Love Stackoverflow

Reputation: 6868

How to split string inside string array?

Below is my string array :

 public string[] categories { get; set; }

Now this categories contains records like below :

 "categories": [
    "electronic,sports",
    "abc,pqr",
    "xyz",
  ]

Input:

string[] categories = { "electronic,sports", "abc,pqr", "xyz"};

Now I want to split values in categories and create records like this but in categories variable only :

So final categories variable should contain output like below:

"categories": [
    "electronic",
    "sports",
    "abc",
    "pqr",
    "xyz",
  ]

So I want my loop to run 5 times; if I loop on to categories variable and further lots of operation is done on this variable only so I don't want to take above final output in other variable.

 foreach (var category in categories)
 {
     //code
 }

Upvotes: 0

Views: 117

Answers (4)

har07
har07

Reputation: 89285

You can use LINQ SelectMany() and then project the result to array :

using System.Linq;


string[] categories = { "electronic,sports", "abc,pqr", "xyz"};
categories = categories.SelectMany(o => o.Split(',')).ToArray();

foreach(var c in categories)
{
    Console.WriteLine(c);
}

demo

output :

electronic
sports
abc
pqr
xyz

Upvotes: 7

Switch386
Switch386

Reputation: 470

Without linq...just using a couple foreach loops.

        string[] categories = new string[] { "electronic,sports", "abc,pqr", "xyz" };

        foreach(var category in categories)
        {
            foreach(var item in category.Split(','))
            {
                Console.WriteLine(item);
            }
        }

Upvotes: 1

pridemkA
pridemkA

Reputation: 124

You can try without if code;

        List<string> temps = new List<string>();
        foreach (var category in categories)
        {
            temps.AddRange(category.Split(',').ToList());
        }
        categories = temps.ToArray();

Upvotes: 2

Mohit S
Mohit S

Reputation: 14044

This might do the trick for you

List<string> newcategories = new List<string>();
foreach(var category in categories)
{
    if(category.Contains(","))
    {
        string[] c = category.Split(',');
        newcategories.Add(c[0]);
        newcategories.Add(c[1]);
    }
    else
    {
        newcategories.Add(category);
    }
}

Upvotes: 1

Related Questions