1

I am trying to get only odd arguments in a list. Here is a piece of my code

static void Main(string[] args)
{
     var swictches = args.ToList().Select((x, index) => (index % 2) == 1);
     var ss = swictches[0];

     string test = doc.ReadAllPages();
     Console.WriteLine(test.Substring(0, 1000));
     Console.Read();
}

In the arguments list it has switches and parameters. I am trying to get all the switches. When I run this code the switches variable looks like this:

false
true
false

instead of like this

-i
-awq
-l
Luke101
  • 63,072
  • 85
  • 231
  • 359

3 Answers3

6

Use Where instead of Select:

var swictches = args.Where((x, index) => (index % 2) == 1).ToList();
  • Where filters items based on specified predicate.
  • Select projects elements from one format into another (from string to bool in your code).

Also, you don't have to call ToList() to use Where/Select. string[] implements IEnumerable<string> as well, so you can just use LINQ on it. Instead of calling ToList at the beginning call it as the last method, to instantiate results into List<string>.

Edit:

As pointed in comments. You should use First when you need just the first element from sequence, instead of calling ToList() and using [0] on the results. It's will be faster:

var ss = args.Where((x, index) => (index % 2) == 1).First();
MarcinJuraszek
  • 124,003
  • 15
  • 196
  • 263
2

var switchesFixed = args.Where((item, index) => index % 2 != 0); //returns Even args

var switchesFixed = args.Where((item, index) => index % 2 == 0); //returns Odd args

Qui_Jon
  • 163
  • 1
  • 10
1

Another variant to find all switches:
args.Where(s => s.StartsWith("-")).ToList()

Vladimir
  • 7,345
  • 4
  • 34
  • 39