【问题标题】:Split strings into a set of grouped array将字符串拆分为一组分组数组
【发布时间】:2018-03-05 14:45:57
【问题描述】:

假设我有两个字符串:

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

我想将它们拆分并将它们组合成一个数组(可能是二维数组)。 例如

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

【问题讨论】:

    标签: c# arrays multidimensional-array


    【解决方案1】:

    在这里使用 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 },其中包含当前索引的两个项目。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2016-04-01
      • 2011-09-24
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多