.Net Tips – Use LINQ to avoid nested loops

Yan Cui

I help clients go faster for less using serverless technologies.

Admit it, we’ve all done it before, writing those nasty nested loops just so we can iterate through multiple lists to get some combination/permutation of the lists, e.g.:

   1: for (int i = 0; i < 10; i++)

   2: {

   3:     for (int j = 0; j < 10; j++)

   4:     {

   5:         for (int k = 0; k < 10; k++)

   6:         {

   7:             // do something

   8:         }

   9:     }

  10: }

This code obviously works and well understood amongst developers, but it’s not very readable and trying to terminate the outer loops from the inner loops is a pain and requires you to use one or more boolean flags which you need to track on every iteration at potentially every level of your loop…

A better way to solve this common problem is to use LINQ to ‘flatten’ the nested loops into a single loop:

   1: var triplets = from I in Enumerable.Range(0, 10)

   2:                from J in Enumerable.Range(0, 10)

   3:                from K in Enumerable.Range(0, 10)

   4:                select new { I, J, K };

   5:

   6: foreach (var triplet in triplets)

   7: {

   8:     // do something

   9: }

Sweet, right? :-)

Whenever you’re ready, here are 3 ways I can help you:

  1. Production-Ready Serverless: Join 20+ AWS Heroes & Community Builders and 1000+ other students in levelling up your serverless game. This is your one-stop shop to level up your serverless skills quickly.
  2. Do you want to know how to test serverless architectures with a fast dev & test loop? Check out my latest course, Testing Serverless Architectures and learn the smart way to test serverless.
  3. I help clients launch product ideas, improve their development processes and upskill their teams. If you’d like to work together, then let’s get in touch.

2 thoughts on “.Net Tips – Use LINQ to avoid nested loops”

  1. @Anonymous – if you mean inside the foreach loop, you will be able to reference them like triplet.I, triplet.J and triplet.K.

    In the LINQ query, you can reference the variables I, J and K directly, for example:

    from I in Enumerable.Range(0, 10)
    from J in Enumerable.Range(0, 10)
    from K in Enumerable.Range(0, 10)
    select new { Sum = I + J + K }

Leave a Comment

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