Home > Back-end >  Instead of if statements use a loop?
Instead of if statements use a loop?

Time:09-21

Is there any way I could use a loop instead of writing out all of these if/else statements? I'm not sure if it is possible and I have looked online and haven't seen very many guides that would help me.

int numberOne = random.Next(id2)   1;
int numberTwo = random.Next(id2)   1;
int numberThree = random.Next(id2)   1;
int numberFour = random.Next(id2)   1;
int numberFive = random.Next(id2)   1;

        if (id1 == 1)
        {
            int total = numberOne;
            string newmessage = "message";
            return Json(newmessage);
        }
        else if(id1 == 2)
        {
            int total = numberOne   numberTwo;
            string newmessage = "message";
            return Json(newmessage);
        }
        else if (id1 == 3)
        {
            int total = numberOne   numberTwo   numberThree;
            string newmessage = "message";
            return Json(newmessage);
        }
        else if (id1 == 4)
        {
            int total = numberOne   numberTwo   numberThree   numberFour;
            string newmessage = "message";
            return Json(newmessage);
        }
        else if (id1 == 5)
        {
            int total = numberOne   numberTwo   numberThree   numberFive;
            string newmessage = "message";
            return Json(newmessage);
        }

CodePudding user response:

What you likely want to do is:

int total = Enumerable.Range(1, id1).Sum(z => random.Next(id2)   1);
string newmessage = "message";
return Json(newmessage);

There is no need for an explicit loop (since Enumerable.Range will do the looping for you).

CodePudding user response:

Since you probably need a loop and not using lambdas, you can go with something like this:

   int total = 0;
   for (int i = 0; i < id1; i  ) 
   {
      total  = random.Next(id2)   1;
   }
   return Json("message"); // I assume you want to return total here;

The reason this works is that if id1 is 1, you'd break out of the loop after doing 1 random.Next. If id2 is 2, then you'd run thru the first number and then add the 2nd number automatically. With this approach, you could support any number, not just up to 5.

CodePudding user response:

I'd go with @mjwills solution, but here's an explanation of how you might do it in a step by step fashion:

The first thing I did was declare random, id1 and id2. I varied id1 during testing. When you post code, you should include this kind of thing, that way the folks help you don't have to reverse engineer what you are thinking:

var id1 = 5;
var id2 = 10;
var random = new Random();

Then, I realize that in each case, you have a chunk of the same code (the last two lines), so I extracted that duplicated code out and put it at the bottom of the loop (and I used NewtonSoft's JsonConvert class to convert things to JSON (which I'm assuming your Json function does) - I have that NuGetted into my test project):

string newMessage = "message";
return JsonConvert.SerializeObject(newMessage);

Finally, here's the loop you were asking about. I initialize total (I could put that initialization in the for loop, but it's clearer this way). Also note that the for loop is non-standard, it loops from 1 to N inclusive (generally for loops are 0 to N-1). This loop is between the initialization code and the final code:

var total = 0;
for (var i = 1; i <= id1;   i)
{
    total  = (random.Next(id2)   1);
}

What @mjwills code does is convert that into a single expression. The Enumerable.Range(1, id1) part generates a collection of consecutive integers starting at 1 and having id1 entries. Then he calls .Sum, passing it a lambda that represents a function to run on each item in the collection before it is summed. My loop basically does the same thing.

Altogether, it looks like this:

var id1 = 5;
var id2 = 10;
var random = new Random();

var total = 0;
for (var i = 1; i <= id1;   i)
{
    total  = (random.Next(id2)   1);
}

string newMessage = "message";
return JsonConvert.SerializeObject(newMessage);

CodePudding user response:

try this, it also allows you init 5 numbers using any algoritm, not just the same

    //var random=new Random();
    //var id2=2;
    //var id1=4;

    var data = new int[]{
    random.Next(id2)   1,
    random.Next(id2)   1,
     random.Next(id2)   1,
     random.Next(id2)   1,
     random.Next(id2)   1
   };

var total=0;
for ( var i = 0; i < id1; i  )
{
     total =data[i];
}
    var newmessage = $"message#{id1.ToString()}, total {total.ToString()} ";
    
    return Json(newmessage);
  •  Tags:  
  • c#
  • Related