CSharp - Calling Where operator with element index

Introduction

We can use the index of the element to do the filtering.

This code will filter the ones with an odd index number to be yielded into the output sequence.

Demo

using System;
using System.Linq;
using System.Collections;
using System.Collections.Generic;
class Program/*from w  w  w.j a  v  a2 s .  com*/
{
    static void Main(string[] args)
    {
          string[] names = {
            "Python", "Java", "Javascript", "Bash", "C++", "Oracle"};
    
          IEnumerable<string> sequence = names.Where((p, i) => (i & 1) == 1);
    
          foreach (string s in sequence)
            Console.WriteLine("{0}", s);

    }
}

Result

Related Topic