如何将多个字符串数组 List<string[]> 连接成一个 string[]

How to join multiple arrays of strings List<string[]> into one string[]

我有这个列表

    // sample data
    List<string[]> ListOfArrays = new List<string[]> { new string[]{ "key1", "key2", "key3" }, 
                                                       new string[]{ "value1", "value2", "value3" },
                                                       new string[]{ "item1", "item2", "item3" , "item4"} };

我想用逗号分隔的字符串连接数组中的所有并行索引,这将导致将 List<string[]> 转换为 string[]

预期结果

     // expected result
     string[] joinedList = new string[] { "key1, value1, item1", 
                                          "key2, value2, item2", 
                                          "key3, value3, item3",
                                          "item4"};

有没有简单的方法可以做到这一点?像

string[] string.JoinMultiple(string delimiter, List<string[]>);

在上面的例子中可以像

一样使用
string[] joinedList = string.JoinMultiple(",", ListOfArrays);

我一直在寻找解决方案,但没有希望。

你可以试试这个:

        string[] joinedList = listOfArrays.SelectMany(
            strings => strings.Select((s, i) => new {s, i}))
            .ToLookup(arg => arg.i, arg => arg.s)
            .Select(grouping => string.Join(",", grouping)).ToArray();

或扩展方法:

    string[] joinedList = listOfArrays.JoinMultiple(",");
    ...
    public static string[] JoinMultiple(this List<string[]> lists,string delimiter)
    {
        return lists.SelectMany(
            strings => strings.Select((s, i) => new {s, i}))
            .ToLookup(arg => arg.i, arg => arg.s)
            .Select(grouping => string.Join(delimiter, grouping)).ToArray();
    }

我只是把这个方法放在一起。它会产生您描述的结果。

public static string[] JoinMultiple(string delimiter, List<string[]> lists)
{
    int maxListLength = lists.Max(l => l.Count());
    string[] result = new string[maxListLength];
    for (int i = 0; i < maxListLength; i++)
    {
        result[i] = String.Join(delimiter,
            lists.Select(l => (i < l.Count()) ? l[i] : null)
                 .Where(s => s != null));
    }
    return result;
}