简体   繁体   中英

Create dynamic foreach loop for sequential search type in C#

First analyze my C# code.

        string[] shape = { "Round", "Square" };
        string[] Size = { "7", "9", "10" };
        string[] type = { "Chocklate", "Honey", "Vanila" };
        string[] top = { "Blank Cake", "Licenced Image Cake", "Personal Image Cake" };
        string[] msg = { "Happy Birthday", "Own Message", "Get Well Soon" };

        List<string> MyPatterns = new List<string>();

        for (int i = 0; i < shape.Length; i++)
        {
            MyPatterns.Add(shape[i]);
            for (int j = 0; j < Size.Length; j++)
            {
                MyPatterns.Add(shape[i] + " - " + Size[j]);
                for (int k = 0; k < type.Length; k++)
                {

                    string A = shape[i] + " - " + Size[j] + " - " + type[k];
                    MyPatterns.Add(A);

                    for (int l = 0; l < top.Length; l++)
                    {
                        string B = shape[i] + " - " + Size[j] + " - " + type[k] + " - " + top[l];
                        MyPatterns.Add(B);

                        for (int m = 0; m < msg.Length; m++)
                        {
                            string C = shape[i] + " - " + Size[j] + " - " + type[k] + " - " + top[l] + " - " + msg[m];
                            MyPatterns.Add(C);

                        }

                    }

                }


            }
        }

Now above example has 5 static arrays shape, size, type, top, msg and above code shows every combination is possible between these arrays. Like Round Round - 7 Round - 7 - Chocklate like this all possible combination.

Screenshot :

在此处输入图片说明

Currently I have static arrays shape, size, type, etc.. So I am manually writing foreach loop for each array inside upper array.

Now suppose these arrays comes dynamically. I Don't know count the will be for example sometimes it must be shape and size some time its must be shape, size and type, and sometime they are completely different.

So how can I dynamically Generates foreach loop for dynamic arrays ?

Group those dynamic arrays into an array, so you have an array of arrays (AKA Jagged Array . This way you can loop through the parent array using foreach .

string[][] arr = new string[5][];
arr[0] = new string [] { "Round", "Square" };
arr[1] = new string [] { "7", "9", "10" };
arr[2] = new string [] { "Chocklate", "Honey", "Vanila" };
arr[3] = new string [] { "Blank Cake", "Licenced Image Cake", "Personal Image Cake" };
arr[4] = new string [] { "Happy Birthday", "Own Message", "Get Well Soon" };

foreach (var a in arr) {
    Console.WriteLine("Array count:  " +  a.Length);
    //Now you can loop through each child array.
    foreach (string val in a) {
        //Do your stuff.
        Console.WriteLine("\t" + val);
    }
}

Here is a demo

This a typical candidate for a recursive implementation:

static void Main(string[] args)
{
    string[] shape = { "Round", "Square" };
    string[] size = { "7", "9", "10" };
    string[] type = { "Chocklate", "Honey", "Vanila" };
    string[] top = { "Blank Cake", "Licenced Image Cake", "Personal Image Cake" };
    string[] msg = { "Happy Birthday", "Own Message", "Get Well Soon" };

    IEnumerable<string[]> productRows = CartesianProductRecursive(new []{ shape, size, type, top, msg });

    foreach (var row in productRows)
    {
        Console.WriteLine("{0}, {1}, {2}, {3}, {4}", row[0], row[1], row[2], row[3], row[4]);
    }
}

public static IEnumerable<string[]> CartesianProductRecursive(IEnumerable<string[]> dimValues)
{
    if (!dimValues.Any())
        yield break;

    string[] firstDimValues = dimValues.First();
    IEnumerable<string[]> lastDimsProduct = CartesianProductRecursive(dimValues.Skip(1));

    if (!lastDimsProduct.Any())
        yield return firstDimValues;

    foreach (string firstDimValue in firstDimValues)
    {
        foreach (string[] lastDimsProductRow in lastDimsProduct)
        {
            yield return new[] {firstDimValue}.Concat(lastDimsProductRow).ToArray();
        }
    }
}

If you are performing tests, you can use NUnit cartesian product feature or NCase test case generator . Both allow to reduce the amount of test cases by generating the pairwise product instead of the cartesian product.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM