If you want to use the index of an item with LINQ in C#, you can use the “index” statement:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using NUnit.Framework;
using NUnit.Framework.SyntaxHelpers;

namespace Ada.Cdf.Test
  public class IntegrationTester
    [Explicit("Not a unittest")]
    public void Test()
      List<string> items = new List<string>();
      items.Add("Item 1");
      items.Add("Item 2");
      items.Add("Item 3");
      items.Add("Item 4");
      items.Add("Item 2");
      items.Add("Item 3");

      var result = items.Select((item, index) => new { index, item });
                   //select new { Name=i, Ind=index };
      foreach (var test in result)
        Console.WriteLine(string.Format("item[{0}] index[{1}]", test.item, test.index));



item[Item 1] index[0]

item[Item 2] index[1]

item[Item 3] index[2]

item[Item 4] index[3]

item[Item 2] index[4]

item[Item 3] index[5]

1 passed, 0 failed, 0 skipped, took 2,81 seconds (NUnit 2.4).


  1. What about LINQ to SQL, I am trying to use the same concept using a database table, but it doesn’t work for me.

    For example:

    var resultado = DB.Orders.Select((orden, index) => new { Index=index,Orden=orden.Employee });

    GridView1.DataSource = resultado;

    I getting this error:

    Unsupported overload used for query operator ‘Select’.

    Description: An unhandled exception occurred during the execution of the current web request. Please review the stack trace for more information about the error and where it originated in the code.

    Exception Details: System.NotSupportedException: Unsupported overload used for query operator ‘Select’.

  2. You can do indirectly as follows:
    List lits = DB.Orders.Select(n =>n).ToList();
    var resultado = lít.Select((orden, index) => new { Index=index,Orden=orden.Employee });

    Sorry my english is not good there is nothing untoward would forgive

    Nguyễn Văn Dương

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.