How can I extract this whole string into 5 columns?
"1;2;3;4;5;A;AAA;AA;AAAA;AAAAA;NA;NA;PASS;YES;NO;test1;test2;test3;test4;test5;Word4;Word5;Word3;Word2;Word1"
Like this:
And I want to put the final result in a List by rows;
eg:
How can I extract this whole string into 5 columns?
"1;2;3;4;5;A;AAA;AA;AAAA;AAAAA;NA;NA;PASS;YES;NO;test1;test2;test3;test4;test5;Word4;Word5;Word3;Word2;Word1"
Like this:
And I want to put the final result in a List by rows;
eg:
The question does not stipulate a final data structure. Let's suppose we want something like this at the end:
List<string[]>
{
string[]{ "1", "A", "NA", "test1", "Word4" },
string[]{ "2", "AAA", "NA", "test2", "Word5" },
...
}
A better structured data structure would be more suitable.
And let's suppose that the input string does not contain words having the separator ;
var data = "1;2;3;4;5;A;AAA;AA;AAAA;AAAAA;NA;NA;PASS;YES;NO;test1;test2;test3;test4;test5;Word4;Word5;Word3;Word2;Word1";
var splitData = data.Split(';');
var columnCount = 5;
// We check that the input data has the right number of elements (multiple of columnCount).
if (splitData.Length % columnCount != 0)
{
throw new InvalidOperationException();
}
var results = splitData
.Select((columnVal, i) => (columnVal, i)) // projection of each element including its index.
.GroupBy( x => x.i % columnCount, // group elements by 'row' [0,5,10,15,20][1,6,11,16,21][2,7,12,17,22]...
x => x.columnVal, // selecting only the value (we don't need the index anymore).
(_, columns) => columns.ToArray()) // putting all column values for each row in an array, here we could map to a different data structure.
.ToList();
// the 'results' variable has the target data structure.
If we display the parsed data on the console:
for (var i = 0; i < results.Count; i++)
{
var row = results[i];
// each column value 'i' is in 'result[i]'
var columnStr = string.Join(" | ", row);
Console.WriteLine($"Row {i} -> {columnStr}");
}
/*
Row 0 -> 1 | A | NA | test1 | Word4
Row 1 -> 2 | AAA | NA | test2 | Word5
Row 2 -> 3 | AA | PASS | test3 | Word3
Row 3 -> 4 | AAAA | YES | test4 | Word2
Row 4 -> 5 | AAAAA | NO | test5 | Word1
*/
Here is the solution with assertion tests
string input = "1;2;3;4;5;A;AAA;AA;AAAA;AAAAA;NA;NA;PASS;YES;NO;test1;test2;test3;test4;test5;Word4;Word5;Word3;Word2;Word1";
var elementSplit = input.Split(';');
int columnNumber = 5;
List<string> result = new List<string>();
for (int columnIndex = 0; columnIndex < columnNumber; columnIndex++)
{
StringBuilder row = new StringBuilder();
for (int i = columnIndex; i < elementSplit.Length; i+= columnNumber)
{
row.Append(elementSplit[i]);
row.Append(";");
}
row.Remove(row.Length - 1, 1);
result.Add(row.ToString());
}
Assert.AreEqual("1;A;NA;test1;Word4", result[0]);
Assert.AreEqual("2;AAA;NA;test2;Word5", result[1]);