Admit it, we’ve all done it before, writ­ing those nasty nested loops just so we can iter­ate through mul­ti­ple 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 obvi­ously works and well under­stood amongst devel­op­ers, but it’s not very read­able and try­ing to ter­mi­nate 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 iter­a­tion at poten­tially every level of your loop…

A bet­ter way to solve this com­mon prob­lem is to use LINQ to ‘flat­ten’ the nested loops into a sin­gle 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? :-)

Share

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

  1. Anonymous says:

    How do you use these I J and K variables?

  2. theburningmonk says:

    @Anonymous — if you mean inside the fore­ach loop, you will be able to ref­er­ence them like triplet.I, triplet.J and triplet.K.

    In the LINQ query, you can ref­er­ence the vari­ables 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 Reply