0

I have an excel with 10 columns, I need to validate the values in each column of this excel separately and that is why I am looping through each column one by one.

Now the validation for each column is different.For some columns I need to compare the values in the columns with the values in certain lists.

These Lists say: List1 List2 List3...

Contain the Valid values.The values entered in the columns should be a part of these lists. So, say the first column should contain only the values that are a part of list 1.

What could be the most efficient way to do this? colcount here is 10, rowcount is 5.

for (int c = 1; c <= colcount; c++)
{
    for (int r = 2; r <= rowcount; r++) 
    {
        string celldata = usedRange.Cells[r,c].Text;
        if (c == 1)
        {
            if (List1.Contains(celldata))
            {
                return true;
            }
            else
            {
                return false;
            }
        }
        else if (c == 2)
        {
            if (List2.Contains(celldata))
            {
                return true;
            }
            else
            {
                return false;
            }
        }
        else if (c == 3)
        {
            if (List3.Length <=10 && regex.IsMatch(celldata))
            {
                return true;
            }
            else
            {
                return false;
            }
        }
    }
}

Can't figure out if I am making some basic mistake.

6
  • 11
    return will exit the entire function.What are you trying to accomplish by returning true and false? Commented Sep 10, 2019 at 16:56
  • In addition to what @DetectivePikachu said, your for loop smells of bad design. Once inside the inner loop you already know the value of c, so I think this could be restructured better. Commented Sep 10, 2019 at 16:59
  • 1
    Please edit your question to explain what you want your code to do, and what the structure of your objects are, to the extent that one can reproduce the situation. Commented Sep 10, 2019 at 17:08
  • Hi, @HereticMonkey I have edited the question. I hope this is fine Commented Sep 11, 2019 at 7:17
  • Hi @Sach I am new to this, if you could please tell me how can I make this efficient Commented Sep 11, 2019 at 7:18

1 Answer 1

1

If you want to get out of the inner loop use break.

The break statement terminates the closest enclosing loop or switch statement in which it appears. Control is passed to the statement that follows the terminated statement, if any.

https://learn.microsoft.com/en-us/dotnet/csharp/language-reference/keywords/break

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.