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!
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.
Performance will be identical to what you posted though – no desire to mislead on that respect. I do prefer this Linq syntax.