3 Comments

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
{
  [TestFixture]
  public class IntegrationTester
  {
    [Test]
    [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));
      }

    }
  }
}

Result

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).

3 Replies to “Get index of an item with LINQ and C#”

  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;
    GridView1.DataBind();

    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

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.

Related Posts

Data flows and good DDD architecture in .NET Core and Entity Framework (EF)

      # Introduction From the blog post at https://medium.com/@jpdeffo/domain-driven-design-ddd-in-microservice-architecture-for-nutshell-19c7c579009a and code at https://github.com/Defcoq/DDD  I have learned how to architect a .NET Core project by using DDD principals. The main thing you will have to realize, when you come from a layered architecture, is that the logical flow of data, does not correspond with the project references in Visual Studio.              # Logical dataflow…