Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Calling fellow code nerds - Alternatives to Nested Loops?

Tags:

c#

loops

linq

It is not uncommon for me (or likely anyone else) to have a list of objects I need to iterate through and then interact with a list of properties. I use a nested loop, like this:

IList<T> listOfObjects;
IList<TProperty> listOfProperties;

foreach (T dataObject in listOfObjects)
{
    foreach (TProperty property in listOfProperties)
    {
        //do something clever and extremely useful here
    }
}

Is this the time and performance tested pattern for this problem? Or is there something more performant, more elegant, or just plain fun (while still being readable and maintainable of course)?

The code above doesn't make me smile. Can someone please help bring some joy to my loop?

Thank you!

Update: I use the term "nerd" in a most positive sense. As part of the wikipedia definition puts it "that refers to a person who passionately pursues intellectual activities". By "code nerd" I mean someone who is concerned about continually improving oneself as a programmer, finding new, novel, and elegant ways of coding that are fast, maintainable, and beautiful! They rejoice to move out of VB6 and want smart people to critique their code and help them smartify themselves. (Note: they also like to make new words that end in -ify).

Final note:

Thank you to Dave R, Earwicker, and TheSoftwareJedi for sending me down the Linq path. It is just the sort of happy code I was looking for!

like image 470
Steve Avatar asked Dec 13 '08 15:12

Steve


People also ask

What is the alternative for nested loop?

Instead of using two for-loops to get the element of an array, you could simply use one loop which is much faster than nested loops. Code (CSharp): public void CreateMatrix(int size){

How do you avoid nested for loops in a code?

You can avoid nested loops with itertools. product() . You can use itertools. product() to get all combinations of multiple lists in one loop and get the same result as nested loops.

Should you avoid nested for loops?

Nesting loops inside of each other in python makes for much harder code to understand, it takes more brain power to understand, and is thus more error prone than if its avoidable.

What is a nested loop in coding?

A nested loop is a loop inside another loop. Although all kinds of loops can be nested, the most common nested loop involves for loops. These loops are particularly useful when displaying multidimensional data. When using these loops, the first iteration of the first loop will initialize, followed by the second loop.


1 Answers

Looks like you are trying to cartesian join two lists, and apply a where clause. Here's a simple example showing the Linq syntax for doing this, which I think is what you are looking for. list1 and list2 can be any IEnumerable, your where clause can contain more detailed logic, and in your select clause you can yank out what you need.

        var list1 = Enumerable.Range(1, 100);
        var list2 = Enumerable.Range(1, 100);

        foreach (var item in from a in list1
                             from b in list2
                             where a % b == 0
                             select new { a, b })
        {
            Console.WriteLine(item);
        };

Performance will be identical to what you posted though - no desire to mislead on that respect. I do prefer this Linq syntax.

like image 199
TheSoftwareJedi Avatar answered Sep 17 '22 13:09

TheSoftwareJedi