Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Split strings into a set of grouped array

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] = ...
}
like image 595
User11040 Avatar asked Jul 30 '26 04:07

User11040


1 Answers

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.

like image 145
fubo Avatar answered Jul 31 '26 17:07

fubo