4

Possible Duplicate:
Is there a simpler way to do this if statement in C#

I have this code:

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

is there any way to do the above like for instance:

while (!txtSource.Text[startPos].ToString() in (" ",",","."))
Community
  • 1
  • 1
Somebody
  • 2,667
  • 14
  • 60
  • 100

4 Answers4

7
while ((new char[] {' ', ',', '.'}).Contains(txtSource.Text[startPos]))
Steven Doggart
  • 43,358
  • 8
  • 68
  • 105
5

LINQ Any() for help:

string text = "some text";
char[] controlChars = { ' ', ',', '.' };
int index = 1;
bool passed = controlChars.Any(c => c == text[index]);
sll
  • 61,540
  • 22
  • 104
  • 156
  • While I question the reasons the author wants a "better" way to improve their code, this is an elegant solution, and does provide some clarity to the code. – Security Hound Jul 06 '12 at 14:02
4
string[] SearchList =  {" ",",","."};

while (SearchList.Contains(txtSource.Text[startPos].ToString() ))
{
   // Do Something
}
David
  • 72,686
  • 18
  • 132
  • 173
  • Nice David! thank you :) – Somebody Jul 06 '12 at 13:56
  • I like @SteveDog's format better, though. He did the same thing in one line of code, and (more properly than my answer) used chars, which also shortened it up and eliminate the need for .ToString(). – David Jul 06 '12 at 14:03
4
private static bool IsStopChar(char c)
{
  switch (c)
  {
    case ' ':
    case ',':
    case '.':
      return false;
    default:
      return true;
  }
}

//...

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

With this solution you avoid collection iteration, memory allocation, initialization,... Modifying cases remains easy.

Guillaume
  • 12,824
  • 3
  • 40
  • 48
  • 1
    -1 need moar LINQ! Just kidding, I upvoted ... this is very straight forward and readable. Shorter is not always better. – jrummell Jul 06 '12 at 14:09