Search code examples
c#yieldyield-return

C#, converting a case statement to a yield statement


I want to convert this statement to build a list of VM images to use in testing into something more elegant using the yield keyword, but the syntax is elluding me.

Desired end goal.

List<VmImages> images;
images[0] - WindowsServer2019
images[1] - WindowsServer2016
images[2] - RhelServer;
images[3] - OpenLogic;

Today the code looks like this:

for (var i = 0; i < LinuxVMs; i++)
{
    switch (i)
    {
        case 0:
            linuxDistros.Add(ConfigLoader.redHat);
            break;
        case 1:
            linuxDistros.Add(ConfigLoader.openLogic);
            break;
        case 2:
            linuxDistros.Add(ConfigLoader.suse);
            break;
        case 3:
            linuxDistros.Add(ConfigLoader.ubuntu);
            break;
    }
}

This feels like a good case to use the yield keyword to simplify the logic into something like this, where I call GetLinuxVMs() for x number of times, where X is the count of LinuxVMs.

private static IEnumerable<VmDistribution> GetLinuxVmDistros()
{
    yield return ConfigLoader.redHat;
    yield return ConfigLoader.openLogic;
    yield return ConfigLoader.suse;
    yield return ConfigLoader.canonical;
}

I'm not sure how to integrate this into my code, this is what I've tried:

for (var i = 0; i < LinuxVMs; i++)
{
    linuxDistros.Add(GetLinuxVmDistros());
}

Since I get an IEnum back from the GetLinuxVmDistros method every time, I am puzzled as to how this is supposed to work at all.


Solution

  • From your stated "desired end goal"

    List<VmImages> images = new() {
        WindowsServer2019,
        WindowsServer2016,
        RhelServer,
        OpenLogic
    }
    

    All the rest of the looping/finagling is just confusing the issue, IMHO