当前位置: 动力学知识库 > 问答 > 编程问答 >

c# - Is it Possible to create an array of Condition Statements?

问题描述:

I am making conditional statements with excel calls and I was wondering if there was a way to have my program check an array of conditions that it loops through, rather than a bunch of "or" statements. My code is as follows:

while(

activesheet.Range["A" + n].Text != "sting 1"

|| activesheet.Range["A" + n].Text != "string 2"

|| activesheet.Range["A" + n].Text != "string 3"...)

{

n++;

}

Is it possible to have an array of conditions that each row of my excel file can be forced to go through? I can't seem to figure it out and have not found any answers or examples yet. I think I can use a 'foreach' call but I am not sure how to implement it for my purpose. Thanks.

网友答案:

You can reverse the logic and use Contains:

var strings = new[] {"sting 1", "string 2", "string 3"};
while(!strings.Contains(activesheet.Range["A" + n].Text))
{
}

However, if you're using Office Interop I would note that Range[] and Text are both COM calls, which are slow. You may see significant improvement by not calling them for each string comparison, and instead comparing against a constant in your while loop:

while(true)
{
    var value = activesheet.Range["A" + n].Text; // one COM call instead of multiple
    if (strings.Contains(value)) break;
}
网友答案:

You can use Linq to turn your code into data which you can iterate through and test like an array - something like this :

List<Func<bool>> stepsList = new List<Func<bool>>
        {
            Condition1,
            Condition2,
            ...
        };

stepsList.TrueForAll(f => f());
网友答案:
var conditions = new List<Func<Range, bool>>();

foreach (Range r in allMyXlsRanges)
{
    while (conditions.TrueForAll(c => c(r)))
    {
        //whatever
    }
}

With this setup you only need to initialize your conditions once:

 conditions.Add(r => r.Text != "string 1");
 conditions.Add(r => r.Text != "string 2");
 //etc.

This is basically the same solution auburg has posted but allowing you to iterate through a collection of ranges which is what I think you are trying to do.

分享给朋友:
您可能感兴趣的文章:
随机阅读: