0

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.

1
  • 1
    @NathanCooper what you are saying is actually very wrong just because i have 46 rep does not mean you should downvote ! i read how to ask carefully i demonstrated the problem very clearly the second code shows you the expected result ! read the question clearly before downvoting Commented Mar 15, 2015 at 23:33

2 Answers 2

2

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();
    }
Sign up to request clarification or add additional context in comments.

1 Comment

Fixed extension method. Thank you.
0

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;
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.