• Blog
  • Info Support
  • Career
  • Training
  • International Group
  • Info Support
  • Blog
  • Career
  • Training
  • International Group
  • Search
logo InfoSupport
  • Latest blogs
  • Popular blogs
  • Experts
      • All
      • Bloggers
      • Speakers
  • Meet us
  • About us
    • nl
    • en
    • .NET
    • 3D printing
    • Advanced Analytics
    • Agile
    • Akka
    • Alexa
    • Algorithms
    • Api's
    • Architectuur
    • Artificial Intelligence
    • ATDD
    • Augmented Reality
    • AWS
    • Azure
    • Big Data
    • Blockchain
    • Business Intelligence
    • Chatbots
    • Cloud
    • Code Combat
    • Cognitive Services
    • Communicatie
    • Containers
    • Continuous Delivery
    • CQRS
    • Cyber Security
    • Dapr
    • Data
    • Data & Analystics
    • Data Science
    • Data Warehousing
    • Databricks
    • DataOps
    • Developers life
    • DevOps
    • Digital Days
    • Digital Twin
    • Docker
    • eHealth
    • Enterprise Architecture
    • Event Sourcing
    • Hacking
    • Infrastructure & Hosting
    • Innovatie
    • Integration
    • Internet of Things
    • Java
    • Machine Learning
    • Microservices
    • Microsoft
    • Microsoft Bot Framework
    • Microsoft Data Platform
    • Mobile Development
    • Mutation Testing
    • Open source
    • Pepper
    • Power BI
    • Privacy & Ethiek
    • Python
    • Quality Assistance & Test
    • Quality Assurance & Test
    • Requirements Management
    • Scala
    • Scratch
    • Security
    • SharePoint
    • Software Architecture
    • Software development
    • Software Factory
    • SQL Server
    • SSL
    • Start-up
    • Startup thinking
    • Stryker
    • Test Quality
    • Testing
    • TLS
    • TypeScript
    • Various
    • Web Development
    • Web-scale IT
    • Xamarin
    • All
    • Bloggers
    • Speakers
Home » Selecting or filtering on the sequence number in Linq
  • Selecting or filtering on the sequence number in Linq

    • By Frank Bakker
    • .NET 14 years ago
    • .NET 0 comments
    • .NET .NET
    Selecting or filtering on the sequence number in Linq

    A few weeks ago I was writing a Linq query where I needed each items sequence number (or index) as a part of the filter expression in a Where operation. To simplify the actual problem let's say I needed to filter out only the odd items. One (wrong) way to do this would be:

    int i = 0;
    var filtered = input.Where(x => i++ % 2 == 1);

    This will appear to work at first but it only works correct the first time the filtered sequence is iterated. I will not get into this to deep here, but it has to do with the lambda updating the outer variable which is a bad idea.
    Fortunately there is a correct (and easier) way to do this. As it turns out the Where extension method has an extra overload that excepts a lambda function with two input parameters. When you use this overload the lambda receives an extra input parameter which indicates the sequence number of the current item. The correct code looks like this.

    var filtered = input.Where((x, i) => i % 2 == 1);

    As I wanted to write the rest of the query in Linq comprehension syntax (yes it does have some advantageous sometimes), I wanted to write something like

    var filtered = from x in input
                   // other Linq stuff           
                   where ???? % 2 == 1
                   select x;

    Comprehension syntax however does not have a built in way to refer to the sequence number (as far as I could find out in 15 min with Google). Bummer 🙁

    I did find that the Select method has an overload just like the Where method, that accepts a lambda with a sequence number parameter. This allows the sequence number to be used in the query's output.

    var withSequenceNumber = input.select((item, index) => new {item, index})

    Just like in the where clause, it is not possible to use the sequence number in comprehension syntax's select clause. It is however possible to mix normal C# syntax and comprehension syntax and make the sequence number available to all the comprehension syntax operators:

    var filtered = from x in input.select((item, index) => new {item, index})
                  // other Linq stuff           
                  where x.index %2 == 1
                  select x.item;

    By first selecting each item along with its sequence number into an anonymous type, the rest of the query can refer to the sequence number as x.index and the item itself as x.item. As an extra bonus the original sequence numbers of the items before filtering are still available after filtering, so they could be used in the select clause to be presented in the ouput.

    Share this

Frank Bakker

View profile

Related IT training

Go to training website

Related Consultancy solutions

Go to infosupport.com

Related blogs

  • Building a custom Kubernetes operator in C#

    Building a custom Kubernetes operator in C# Willem Meints - 2 months ago

  • Transform SpecFlow Table Column

    Transform SpecFlow Table Column Ronald Bosma - 5 months ago

  • Building a passwordless login flow with WebAuthn and th…

    Building a passwordless login flow with WebAuthn and th… Willem Meints - 7 months ago

Data Discovery Channel

  • Explainable AI - Break open the blackbox

  • Toekomstvaste microservice data architecturen

  • Modern Data Platform

Nieuwsbrief

* verplichte velden

Contact

  • Head office NL
  • Kruisboog 42
  • 3905 TG Veenendaal
  • T +31 318 552020
  • Call
  • Mail
  • Directions
  • Head office BE
  • Generaal De Wittelaan 17
  • bus 30 2800 Mechelen
  • T +32 15 286370
  • Call
  • Mail
  • Directions

Follow us

  • Twitter
  • Facebook
  • Linkedin
  • Youtube

Newsletter

Sign in

Extra

  • Media Library
  • Disclaimer
  • Algemene voorwaarden
  • ISHBS Webmail
  • Extranet
Beheer cookie toestemming
Deze website maakt gebruik van Functionele en Analytische cookies voor website optimalisatie en statistieken.
Functioneel Always active
De technische opslag of toegang is strikt noodzakelijk voor het legitieme doel het gebruik mogelijk te maken van een specifieke dienst waarom de abonnee of gebruiker uitdrukkelijk heeft gevraagd, of met als enig doel de uitvoering van de transmissie van een communicatie over een elektronisch communicatienetwerk.
Voorkeuren
De technische opslag of toegang is noodzakelijk voor het legitieme doel voorkeuren op te slaan die niet door de abonnee of gebruiker zijn aangevraagd.
Statistieken
De technische opslag of toegang die uitsluitend voor statistische doeleinden wordt gebruikt. De technische opslag of toegang die uitsluitend wordt gebruikt voor anonieme statistische doeleinden. Zonder dagvaarding, vrijwillige naleving door uw Internet Service Provider, of aanvullende gegevens van een derde partij, kan informatie die alleen voor dit doel wordt opgeslagen of opgehaald gewoonlijk niet worden gebruikt om je te identificeren.
Marketing
De technische opslag of toegang is nodig om gebruikersprofielen op te stellen voor het verzenden van reclame, of om de gebruiker op een website of over verschillende websites te volgen voor soortgelijke marketingdoeleinden.
Manage options Manage services Manage vendors Read more about these purposes
Voorkeuren
{title} {title} {title}