List<string> arguments = new List<string>(Environment.GetCommandLineArgs().Skip(1).Take(4));
int variant = consoleOptions.HandleInput(arguments);
public int HandleInput(List<string> input)
{
int variant = 0;
//for (int i = 0; i < input.Count; i++)
//{
// if (input[i].Contains("-s"))
// {
// variant = 1;
// }
//}
if (input[0].Contains("-s"))
{
variant = 1;
if (!String.IsNullOrWhiteSpace(input[1]) && !String.IsNullOrWhiteSpace(input[2]))
{
variant = 2;
}
if (!String.IsNullOrWhiteSpace(input[3]))
{
variant = 3;
}
}
return variant;
}
I’m starting my application from Commandline.
Then I get a List of Strings (max 4).
What I want to do now is:
if the first String in List is “-s” then variant = 1
if the second and third string isn’t Empty then variant = 2
if the fourth string isn’t Empty then variant = 3
I tried some things (Code above), but the problem is, if I only get the first String (one item),
The Compiler crashes on other place (checking Second string, cause Index not accessible)..
What would be the best method?
The
Take(4)doesn’t guarantee that you’ll have 4 elements, it just means you won’t have more than 4. So you have to check the list length.