C# - 在预定义的字符串数组中查找字符串的位置

Ler*_*ica 0 c# arrays string

我有一个从字母一个预定义的字符串数组AQ:

string[] SkippedAreasArray = new string[] {"A", "B", "C", "D", "E", "F", "G",
            "H", "I", "J", "K", "L", "M", "N", "O", "P", "Q"};
Run Code Online (Sandbox Code Playgroud)

TextBoxWindows窗体内部,用户可以像这样输入skippedAreas:A,B,C,D...有验证和限制只能使用字母和逗号,因此输入保证采用这种格式.

我所做的是获取用户输入并填充另一个字符串数组:

string[] SkippedAreasFromForm = new string[17];
...
SkippedAreasFromForm = (txtSkippedAreas.Text).Split(',');
Run Code Online (Sandbox Code Playgroud)

现在是我寻求帮助的棘手部分.用户必须输入Number of areas例如- 3.这意味着他与唯一的工作A,BC.如果区域的数量为2,那么他只能用AB,如果区域的数量为4,然后A,B,CD提供等.

我需要的是检查SkippedAreasFromForm填充了用户输入的数组中是否存在与上述条件不匹配的区域.

这在编码方面意味着什么 - 我需要从中获取每个元素 SkippedAreasFromForm,从预定义中获取它的整数值,SkippedAreasArray并查看该值是否等于或大于(> =)他输入的值为"区域数".如果存在超出所选数字范围的区域,则应显示错误.

我现在拥有的是:

foreach (string tempAreaValue in SkippedAreasFromForm)
                {
                    for (int i = 0; i < SkippedAreasArray.Length; i++)
                    {
                        if (tempAreaValue == SkippedAreasArray[i])
                        {
                            if ((i + 1) > entity.AreasCnt)
                            {
                                MessageBox.Show("You must use areas only within the Number of Areas scope!", "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
                                txtSkippedAreas.Focus();
                                return false;
                            }
                        }
                    }
                }
Run Code Online (Sandbox Code Playgroud)

对于少数测试我做了它的工作.但首先 - 至少对我而言似乎过于复杂.第二 - 我不确定这个算法是否正常工作,或者我只是运气得到了正确的结果.第三 - 我现在正在编写C#2个月,这对我来说似乎是LINQ表达的一个很好的候选者 - 你认为使用LINQ会更好吗?我会很感激帮助你进行转换.

Jon*_*eet 5

我想你只是在寻找IndexOf:

int index = SkippedAreasArray.IndexOf(tempAreaValue);
if (index >= entity.AreasCnt)
{
    ...
}
Run Code Online (Sandbox Code Playgroud)

(您可能还需要检查index.为-1,如果该元素在列表中是不是在所有可能会出现的同时,考虑重复-可以在用户输入A,A,A?)