Home > Enterprise >  Execute foreach loop fully, though if statement get executed in loop
Execute foreach loop fully, though if statement get executed in loop

Time:01-16

I am using foreach loop, now what I want is this loop should run for each elements in that loop count.

Once that is finished then it should return to the function, here in this loop I have also use if statement.

But problem is when first time if statement is executing it is returning to that function without finishing whole foreach loop count.

But instead of that, it should run foreach loop fully and then return with that messages.

Below is code :

foreach (var field in fields.OrderBy(x => x.Sequence))
{
   if (!header.Any(x => x.Sequence == field.Sequence && x.Name == field.Name))
   {
      var colName = header.Where(x => x.Sequence == field.Sequence).Select(x => x.ExcelColName).FirstOrDefault();
      var newheaderName = header.Where(x => x.Sequence == field.Sequence).Select(x => x.Name).FirstOrDefault();
      message = string.Format("In cell {0}1, column '{1}' was expected but '{2}' was there. The Excel data will NOT be imported.", colName, field.Name, newheaderName);
      messageList.Add(message); // Here after adding all message in list, then it should return to calling function
   } else
   {

   }
   return null;
}

CodePudding user response:

Your return is in your foreach loop. Bring it out of the scope of the foreach.

CodePudding user response:

Let's say you call your function like this.

CallMyFunction();
...

If you don't need anything to be returned from this function then use void like this.

public void CallMyFunction()
{
    foreach (var field in fields.OrderBy(x => x.Sequence))
    {
        if (!header.Any(x => x.Sequence == field.Sequence && x.Name == field.Name))
        {
            var colName = header.Where(x => x.Sequence == field.Sequence).Select(x => x.ExcelColName).FirstOrDefault();
            var newheaderName = header.Where(x => x.Sequence == field.Sequence).Select(x => x.Name).FirstOrDefault();
            message = string.Format("In cell {0}1, column '{1}' was expected but '{2}' was there. The Excel data will NOT be imported.", colName, field.Name, newheaderName);
            messageList.Add(message); // Here after adding all message in list, then it should return to calling function
        } else
        {

        } // Remove entirely the return.
    }

That way your loop will fully run.

  •  Tags:  
  • Related