so out of the following 3 examples that do the same thing i really lean towards the first but is it really overkill and an abuse of linq to do things that way where you can create it all as an expression
var Rand = new Random();
Hosts = "abcdef".Select(x =>
{
return new HostMachineToUpdate(x + "_Host",
Enumerable.Range(1, Rand.Next(3, 8))
.Select(y => new VirtualMachineToUpdate(x + y.ToString() + "_VM")).
ToList()
);
}
)
.ToList();
//traditional
Hosts = new List<HostMachineToUpdate>();
for (int x = (int)'a'; x < (int)'e'; x++)
{
var Guests = new List<VirtualMachineToUpdate>();
for (int y = 1; y < (new Random().Next(3, 8));y++ )
{
Guests.Add(new VirtualMachineToUpdate((char)x + y.ToString() + "_VM"));
}
Hosts.Add(new HostMachineToUpdate((char) x + "Host",Guests));
}
//very traditional.
Hosts = new List<HostMachineToUpdate>();
int lower = (int)'a';
int upper = (int)'e';
for (int x = lower; x < upper; x++)
{
List<VirtualMachineToUpdate> Guests = new List<VirtualMachineToUpdate>();
int randomItemNum = new Random().Next(3, 8);
for (int y = 1; y < randomItemNum; y++)
{
string vmname = (char)x + y.ToString() + "_VM";
VirtualMachineToUpdate vm = new VirtualMachineToUpdate(vmname);
Guests.Add(vm);
}
string hostname = (char)x + "Host";
HostMachineToUpdate host = new HostMachineToUpdate(hostname, Guests);
Hosts.Add(host);
}
I personally don’t like the amount of casting used in your traditional solution.
Is all the casting actually needed ?
Wouldn’t this (untested) code also do what is required?