CSharp - Reference element index in Select operator

Introduction

The following code shows how to embed the index that is passed to our selector method into our output sequence's element type.

Demo

using System;
using System.Linq;
using System.Collections;
using System.Collections.Generic;

class Program/*from  w ww  . ja  v a2  s .c o m*/
{
    static void Main(string[] args)
    {
          string[] names = {
            "Python", "Java", "Javascript", "Bash", "C++", "Oracle"};
    
          var nameObjs = names.Select((p, i) => new { Index = i, LastName = p });
    
          foreach (var item in nameObjs)
            Console.WriteLine("{0}.  {1}", item.Index + 1, item.LastName);

    }
}

Result

This example will output the index number plus one, followed by the name.

Related Topic