我有这个清单
// 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);
我一直在寻找解决方案,但没有希望。
答案 0 :(得分:2)
你可以试试这个:
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();
}
答案 1 :(得分:0)
我把这个方法放在一起。它会产生您描述的结果。
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;
}