I am trying to do some string maniplation for a product import, unfortunely I have some duplicate data, which if left in would assign products to categories that I don't want products assigned to.
I have the following string :
Category A|Category A > Sub Category 1|Category B|Category C|Category C > Sub Category 2
The outcome I would like be:
Category A>Sub Category 1
Category B
Category C>Sub Category 2
First I split on the (|) which gives me:
Category A
Category A > Sub Category 1
Category B
Category C
Category C > Sub Category 2
I was then loop through this list and spilt on the (>)
But I don't know how to merge the results for example Category A\ Sub Category 1
Below is the code. This will be used to process approx 1200 rows, so I am trying to make it has quick as possible.
static void Main(string[] args)
{
string strProductCategories = "Category A|Category A > Sub Category 1|Category B|Category C|Category C > Sub Category 2";
List<string> firstSplitResults = strProductCategories.SplitAndTrim('|');
List<List<string>> secondSplitResults = new List<List<string>>();
foreach( string firstSplitResult in firstSplitResults )
{
List<string> d = firstSplitResult.SplitAndTrim('>');
secondSplitResults.Add(d);
}
// PrintResults(firstSplitResults);
PrintResults2(secondSplitResults);
}
public static void PrintResults(List<string> results)
{
foreach( string value in results)
{
Console.WriteLine(value);
}
}
public static void PrintResults2(List<List<string>> results)
{
foreach(List<string> parent in results)
{
foreach (string value in parent)
{
Console.Write(value);
}
Console.WriteLine(".....");
}
}
}
public static class StringExtensions
{
public static List<string> SplitAndTrim(this string value, char delimter)
{
if( string.IsNullOrWhiteSpace( value))
{
return null;
}
return value.Split(delimter).Select(i => i.Trim()).ToList();
}
}
Once I have got the list correct I will rejoin the list with the (\).
Any help would be very useful.
UPDATE
The data is coming from a CSV so it could have n number of levels.
So for example :
Category A -> THIS IS DATA IS REDUNDANT
Category A > Sub Category 1 -> THIS IS DATA IS REDUNDANT
Category A > Sub Category 1 > Sub Sub Category 1
Category A > Sub Category 1 > Sub Sub Category 2
Would result in :
Category A > Sub Category 1 > Sub Sub Category 1
Category A > Sub Category 1 > Sub Sub Category 2
Simon