将字符串拆分为一组分组数组

时间:2018-03-05 14:45:57

标签: c# arrays multidimensional-array

假设我有两个字符串:

Hello,C#,Black,March
World,Java,White,April

我想将它们分开并将它们组合成一个数组(可能是二维数组)。 E.g。

 { "Hello", "World"}
 { "C#", "Java"}
 { "Black", "White"}
 { "March", "April" }

我的尝试:

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] = ...
}

1 个答案:

答案 0 :(得分:10)

Linq Zip的使用在这里有意义:

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()迭代Split()的两个结果数组,并为每个索引创建一个包含当前索引的两个项目的新数组(s1, s2) => new string[] { s1, s2 }