Suppose I have two string:
Hello,C#,Black,March
World,Java,White,April
I want to split them and group them together into an array (maybe 2-dimensional array). E.g.
{ "Hello", "World"}
{ "C#", "Java"}
{ "Black", "White"}
{ "March", "April" }
My attempt:
string[] arr1 = str1.Split(',').Select(s => s.Trim()).ToArray();
string[] arr2 = str2.Split(',').Select(s => s.Trim()).ToArray();
if (arr1.Length == arr2.Length)
{
string[,] groupedValue = new string[arr1.Count(), arr2.Count()];
//groupedValue[0, 0] = ...
}
Usage of Linq Zip makes sense here:
string str1 = "Hello,C#,Black,March";
string str2 = "World,Java,White,April";
string[][] result = str1.Split(',')
.Zip(
str2.Split(','),
(s1, s2) => new string[] { s1, s2 }
)
.ToArray();
Zip() iterates both result arrays of Split() and creates for each index a new array (s1, s2) => new string[] { s1, s2 } containing both items of the current index.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With