Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Combining arrays of strings together

Tags:

arrays

c#

.net

linq

I'm looking to combine the contents of two string arrays, into a new list that has the contents of both joined together.

string[] days = { "Mon", "Tue", "Wed" };
string[] months = { "Jan", "Feb", "Mar" };

// I want the output to be a list with the contents
// "Mon Jan", "Mon Feb", "Mon Mar", "Tue Jan", "Tue Feb" etc...

How can I do it ? For when it's only two arrays, the following works and is easy enough:

List<string> CombineWords(string[] wordsOne, string[] wordsTwo)
{
    var combinedWords = new List<string>();
    foreach (var wordOne in wordsOne)
    {
        foreach (string wordTwo in wordsTwo)
        {
            combinedWords.Add(wordOne + " " + wordTwo);
        }
    }
    return combinedWords;
}

But I'd like to be able to pass varying numbers of arrays in (i.e. to have a method with the signature below) and have it still work.

List<string> CombineWords(params string[][] arraysOfWords)
{
    // what needs to go here ?
}

Or some other solution would be great. If it's possible to do this simply with Linq, even better!

like image 553
Michael Low Avatar asked Oct 04 '11 09:10

Michael Low


Video Answer


1 Answers

What you want to do is actually a cartesian product of all the arrays of words, then join the words with spaces. Eric Lippert has a simple implementation of a Linq cartesian product here. You can use it to implement CombineWords:

List<string> CombineWords(params string[][] arraysOfWords)
{
    return CartesianProduct(arraysOfWords)
            .Select(x => string.Join(" ", x))
            .ToList();
}
like image 164
Thomas Levesque Avatar answered Sep 30 '22 08:09

Thomas Levesque