everyday learn a new thing!! IEnumerable.ZIP for brekfast.
Whoaaaa!
I am sometimes impressed with my ignorance and inability to learn new things, especially that the incredible stuff is already there for YEARS!
Today I was reviewing a great git repository with algorithms and fond a ZIP linq function. I was looking at it like a cow is looking for a newborn, my jaw dropped to the keyboard and euuureeeka!! no more for in for loops!!
Zip solves a simple problem, allows us to make an union/operation on elements on two enumerable objects (arrays, lists, etc) documentation here
The example from MS docs is clear, and easy to swallow, but if the input objects have different number of elements, then we will get a truncation.
As the function looks cool, it also works nice,
As IEnumerable is a basic way of having collections, it is very fast as well. As I was not able to hold off myself from LINQPad to make a test.
See this listing below
pretty easy code right?
but now see the benchmark results.
Accessing IE using element at wil iterate the collection every time it is invoked, so pretty slow way if we are in the loop.
So from now on, no for loops having internal for loops to process two separate lists or arrays.
The ZIP is very easy to use - see below screenshot. I have a table with a test data, took first 100 records, then next 100 and created a tuple with merged string values - that is easy and cool.
Please share in comments what new you learned today!!
Have a good mood :D
Comments
Post a Comment