Reputation: 6868
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
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);
}
output :
electronic
sports
abc
pqr
xyz
Upvotes: 7
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
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
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