如何使用c#改进此代码

时间:2012-07-06 13:49:35

标签: c# string

  

可能重复:
  Is there a simpler way to do this if statement in C#

我有这段代码:

while ((txtSource.Text[startPos].ToString() == " ") || 
       (txtSource.Text[startPos].ToString() == ",") || 
       (txtSource.Text[startPos].ToString() == ".")))
        {
            // do something
        }

有没有办法像上面这样做:

while (!txtSource.Text[startPos].ToString() in (" ",",","."))

4 个答案:

答案 0 :(得分:7)

while ((new char[] {' ', ',', '.'}).Contains(txtSource.Text[startPos]))

答案 1 :(得分:5)

LINQ Any()寻求帮助:

string text = "some text";
char[] controlChars = { ' ', ',', '.' };
int index = 1;
bool passed = controlChars.Any(c => c == text[index]);

答案 2 :(得分:4)

string[] SearchList =  {" ",",","."};

while (SearchList.Contains(txtSource.Text[startPos].ToString() ))
{
   // Do Something
}

答案 3 :(得分:4)

private static bool IsStopChar(char c)
{
  switch (c)
  {
    case ' ':
    case ',':
    case '.':
      return false;
    default:
      return true;
  }
}

//...

  while (!IsStopChar(txtSource.Text[startPos]))
  {
    //...
  }

使用此解决方案可以避免收集迭代,内存分配,初始化,... 修改案例仍然很容易。