Reputation: 300
I have this list
// sample data
List<string[]> ListOfArrays = new List<string[]> { new string[]{ "key1", "key2", "key3" },
new string[]{ "value1", "value2", "value3" },
new string[]{ "item1", "item2", "item3" , "item4"} };
i want to join all paralleled indexes in the array with comma delimited string, this will result in converting List<string[]>
to string[]
The expected result
// expected result
string[] joinedList = new string[] { "key1, value1, item1",
"key2, value2, item2",
"key3, value3, item3",
"item4"};
is there a simple way to do this ? something like
string[] string.JoinMultiple(string delimiter, List<string[]>);
in the above case could be used like
string[] joinedList = string.JoinMultiple(",", ListOfArrays);
i've been searching a lot to find a solution for this but with no hope.
Upvotes: 0
Views: 266
Reputation: 8131
You can try this:
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();
or extension method:
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();
}
Upvotes: 2
Reputation: 67223
I just put this method together. It produces the results you described.
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;
}
Upvotes: 0